|
{
|
|
"language": "Solidity",
|
|
"sources": {
|
|
"contracts/prize-pool/stake/StakePrizePool.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"../PrizePool.sol\";\n\ncontract StakePrizePool is PrizePool {\n\n IERC20Upgradeable private stakeToken;\n\n event StakePrizePoolInitialized(address indexed stakeToken);\n\n /// @notice Initializes the Prize Pool and Yield Service with the required contract connections\n /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool\n /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount\n /// @param _stakeToken Address of the stake token\n function initialize (\n RegistryInterface _reserveRegistry,\n ControlledTokenInterface[] memory _controlledTokens,\n uint256 _maxExitFeeMantissa,\n IERC20Upgradeable _stakeToken\n )\n public\n initializer\n {\n PrizePool.initialize(\n _reserveRegistry,\n _controlledTokens,\n _maxExitFeeMantissa\n );\n\n require(address(_stakeToken) != address(0), \"StakePrizePool/stake-token-not-zero-address\");\n stakeToken = _stakeToken;\n\n emit StakePrizePoolInitialized(address(stakeToken));\n }\n\n /// @notice Determines whether the passed token can be transferred out as an external award.\n /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The\n /// prize strategy should not be allowed to move those tokens.\n /// @param _externalToken The address of the token to check\n /// @return True if the token may be awarded, false otherwise\n function _canAwardExternal(address _externalToken) internal override view returns (bool) {\n return address(stakeToken) != _externalToken;\n }\n\n /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.\n /// @return The underlying balance of asset tokens\n function _balance() internal override returns (uint256) {\n return stakeToken.balanceOf(address(this));\n }\n\n function _token() internal override view returns (IERC20Upgradeable) {\n return stakeToken;\n }\n\n /// @notice Supplies asset tokens to the yield source.\n /// @param mintAmount The amount of asset tokens to be supplied\n function _supply(uint256 mintAmount) internal override {\n // no-op because nothing else needs to be done\n }\n\n /// @notice Redeems asset tokens from the yield source.\n /// @param redeemAmount The amount of yield-bearing tokens to be redeemed\n /// @return The actual amount of tokens that were redeemed.\n function _redeem(uint256 redeemAmount) internal override returns (uint256) {\n return redeemAmount;\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
|
|
},
|
|
"contracts/prize-pool/PrizePool.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol\";\nimport \"@pooltogether/fixed-point/contracts/FixedPoint.sol\";\n\nimport \"../external/compound/ICompLike.sol\";\nimport \"../registry/RegistryInterface.sol\";\nimport \"../reserve/ReserveInterface.sol\";\nimport \"../token/TokenListenerInterface.sol\";\nimport \"../token/TokenListenerLibrary.sol\";\nimport \"../token/ControlledToken.sol\";\nimport \"../token/TokenControllerInterface.sol\";\nimport \"../utils/MappedSinglyLinkedList.sol\";\nimport \"./PrizePoolInterface.sol\";\n\n/// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool.\n/// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract.\n/// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens\nabstract contract PrizePool is PrizePoolInterface, OwnableUpgradeable, ReentrancyGuardUpgradeable, TokenControllerInterface, IERC721ReceiverUpgradeable {\n using SafeMathUpgradeable for uint256;\n using SafeCastUpgradeable for uint256;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using SafeERC20Upgradeable for IERC721Upgradeable;\n using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;\n using ERC165CheckerUpgradeable for address;\n\n /// @dev Emitted when an instance is initialized\n event Initialized(\n address reserveRegistry,\n uint256 maxExitFeeMantissa\n );\n\n /// @dev Event emitted when controlled token is added\n event ControlledTokenAdded(\n ControlledTokenInterface indexed token\n );\n\n /// @dev Emitted when reserve is captured.\n event ReserveFeeCaptured(\n uint256 amount\n );\n\n event AwardCaptured(\n uint256 amount\n );\n\n /// @dev Event emitted when assets are deposited\n event Deposited(\n address indexed operator,\n address indexed to,\n address indexed token,\n uint256 amount,\n address referrer\n );\n\n /// @dev Event emitted when interest is awarded to a winner\n event Awarded(\n address indexed winner,\n address indexed token,\n uint256 amount\n );\n\n /// @dev Event emitted when external ERC20s are awarded to a winner\n event AwardedExternalERC20(\n address indexed winner,\n address indexed token,\n uint256 amount\n );\n\n /// @dev Event emitted when external ERC20s are transferred out\n event TransferredExternalERC20(\n address indexed to,\n address indexed token,\n uint256 amount\n );\n\n /// @dev Event emitted when external ERC721s are awarded to a winner\n event AwardedExternalERC721(\n address indexed winner,\n address indexed token,\n uint256[] tokenIds\n );\n\n /// @dev Event emitted when assets are withdrawn instantly\n event InstantWithdrawal(\n address indexed operator,\n address indexed from,\n address indexed token,\n uint256 amount,\n uint256 redeemed,\n uint256 exitFee\n );\n\n event ReserveWithdrawal(\n address indexed to,\n uint256 amount\n );\n\n /// @dev Event emitted when the Liquidity Cap is set\n event LiquidityCapSet(\n uint256 liquidityCap\n );\n\n /// @dev Event emitted when the Credit plan is set\n event CreditPlanSet(\n address token,\n uint128 creditLimitMantissa,\n uint128 creditRateMantissa\n );\n\n /// @dev Event emitted when the Prize Strategy is set\n event PrizeStrategySet(\n address indexed prizeStrategy\n );\n\n /// @dev Emitted when credit is minted\n event CreditMinted(\n address indexed user,\n address indexed token,\n uint256 amount\n );\n\n /// @dev Emitted when credit is burned\n event CreditBurned(\n address indexed user,\n address indexed token,\n uint256 amount\n );\n\n /// @dev Emitted when there was an error thrown awarding an External ERC721\n event ErrorAwardingExternalERC721(bytes error);\n\n\n struct CreditPlan {\n uint128 creditLimitMantissa;\n uint128 creditRateMantissa;\n }\n\n struct CreditBalance {\n uint192 balance;\n uint32 timestamp;\n bool initialized;\n }\n\n /// @notice Semver Version\n string constant public VERSION = \"3.4.1\";\n\n /// @dev Reserve to which reserve fees are sent\n RegistryInterface public reserveRegistry;\n\n /// @dev An array of all the controlled tokens\n ControlledTokenInterface[] internal _tokens;\n\n /// @dev The Prize Strategy that this Prize Pool is bound to.\n TokenListenerInterface public prizeStrategy;\n\n /// @dev The maximum possible exit fee fraction as a fixed point 18 number.\n /// For example, if the maxExitFeeMantissa is \"0.1 ether\", then the maximum exit fee for a withdrawal of 100 Dai will be 10 Dai\n uint256 public maxExitFeeMantissa;\n\n /// @dev The total funds that have been allocated to the reserve\n uint256 public reserveTotalSupply;\n\n /// @dev The total amount of funds that the prize pool can hold.\n uint256 public liquidityCap;\n\n /// @dev the The awardable balance\n uint256 internal _currentAwardBalance;\n\n /// @dev Stores the credit plan for each token.\n mapping(address => CreditPlan) internal _tokenCreditPlans;\n\n /// @dev Stores each users balance of credit per token.\n mapping(address => mapping(address => CreditBalance)) internal _tokenCreditBalances;\n\n /// @notice Initializes the Prize Pool\n /// @param _controlledTokens Array of ControlledTokens that are controlled by this Prize Pool.\n /// @param _maxExitFeeMantissa The maximum exit fee size\n function initialize (\n RegistryInterface _reserveRegistry,\n ControlledTokenInterface[] memory _controlledTokens,\n uint256 _maxExitFeeMantissa\n )\n public\n initializer\n {\n require(address(_reserveRegistry) != address(0), \"PrizePool/reserveRegistry-not-zero\");\n uint256 controlledTokensLength = _controlledTokens.length;\n _tokens = new ControlledTokenInterface[](controlledTokensLength);\n\n for (uint256 i = 0; i < controlledTokensLength; i++) {\n ControlledTokenInterface controlledToken = _controlledTokens[i];\n _addControlledToken(controlledToken, i);\n }\n __Ownable_init();\n __ReentrancyGuard_init();\n _setLiquidityCap(uint256(-1));\n\n reserveRegistry = _reserveRegistry;\n maxExitFeeMantissa = _maxExitFeeMantissa;\n\n emit Initialized(\n address(_reserveRegistry),\n maxExitFeeMantissa\n );\n }\n\n /// @dev Returns the address of the underlying ERC20 asset\n /// @return The address of the asset\n function token() external override view returns (address) {\n return address(_token());\n }\n\n /// @dev Returns the total underlying balance of all assets. This includes both principal and interest.\n /// @return The underlying balance of assets\n function balance() external returns (uint256) {\n return _balance();\n }\n\n /// @dev Checks with the Prize Pool if a specific token type may be awarded as an external prize\n /// @param _externalToken The address of the token to check\n /// @return True if the token may be awarded, false otherwise\n function canAwardExternal(address _externalToken) external view returns (bool) {\n return _canAwardExternal(_externalToken);\n }\n\n /// @notice Deposit assets into the Prize Pool in exchange for tokens\n /// @param to The address receiving the newly minted tokens\n /// @param amount The amount of assets to deposit\n /// @param controlledToken The address of the type of token the user is minting\n /// @param referrer The referrer of the deposit\n function depositTo(\n address to,\n uint256 amount,\n address controlledToken,\n address referrer\n )\n external override\n nonReentrant\n onlyControlledToken(controlledToken)\n canAddLiquidity(amount)\n {\n address operator = _msgSender();\n\n _mint(to, amount, controlledToken, referrer);\n\n _token().safeTransferFrom(operator, address(this), amount);\n _supply(amount);\n\n emit Deposited(operator, to, controlledToken, amount, referrer);\n }\n\n /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit.\n /// @param from The address to redeem tokens from.\n /// @param amount The amount of tokens to redeem for assets.\n /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship)\n /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn.\n /// @return The actual exit fee paid\n function withdrawInstantlyFrom(\n address from,\n uint256 amount,\n address controlledToken,\n uint256 maximumExitFee\n )\n external override\n nonReentrant\n onlyControlledToken(controlledToken)\n returns (uint256)\n {\n (uint256 exitFee, uint256 burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);\n require(exitFee <= maximumExitFee, \"PrizePool/exit-fee-exceeds-user-maximum\");\n\n // burn the credit\n _burnCredit(from, controlledToken, burnedCredit);\n\n // burn the tickets\n ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount);\n\n // redeem the tickets less the fee\n uint256 amountLessFee = amount.sub(exitFee);\n uint256 redeemed = _redeem(amountLessFee);\n\n _token().safeTransfer(from, redeemed);\n\n emit InstantWithdrawal(_msgSender(), from, controlledToken, amount, redeemed, exitFee);\n\n return exitFee;\n }\n\n /// @notice Limits the exit fee to the maximum as hard-coded into the contract\n /// @param withdrawalAmount The amount that is attempting to be withdrawn\n /// @param exitFee The exit fee to check against the limit\n /// @return The passed exit fee if it is less than the maximum, otherwise the maximum fee is returned.\n function _limitExitFee(uint256 withdrawalAmount, uint256 exitFee) internal view returns (uint256) {\n uint256 maxFee = FixedPoint.multiplyUintByMantissa(withdrawalAmount, maxExitFeeMantissa);\n if (exitFee > maxFee) {\n exitFee = maxFee;\n }\n return exitFee;\n }\n\n /// @notice Updates the Prize Strategy when tokens are transferred between holders.\n /// @param from The address the tokens are being transferred from (0 if minting)\n /// @param to The address the tokens are being transferred to (0 if burning)\n /// @param amount The amount of tokens being trasferred\n function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) {\n if (from != address(0)) {\n uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from);\n // first accrue credit for their old balance\n uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0);\n\n if (from != to) {\n // if they are sending funds to someone else, we need to limit their accrued credit to their new balance\n newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance);\n }\n\n _updateCreditBalance(from, msg.sender, newCreditBalance);\n }\n if (to != address(0) && to != from) {\n _accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0);\n }\n // if we aren't minting\n if (from != address(0) && address(prizeStrategy) != address(0)) {\n prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender);\n }\n }\n\n /// @notice Returns the balance that is available to award.\n /// @dev captureAwardBalance() should be called first\n /// @return The total amount of assets to be awarded for the current prize\n function awardBalance() external override view returns (uint256) {\n return _currentAwardBalance;\n }\n\n /// @notice Captures any available interest as award balance.\n /// @dev This function also captures the reserve fees.\n /// @return The total amount of assets to be awarded for the current prize\n function captureAwardBalance() external override nonReentrant returns (uint256) {\n uint256 tokenTotalSupply = _tokenTotalSupply();\n\n // it's possible for the balance to be slightly less due to rounding errors in the underlying yield source\n uint256 currentBalance = _balance();\n uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0;\n uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0;\n\n if (unaccountedPrizeBalance > 0) {\n uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance);\n if (reserveFee > 0) {\n reserveTotalSupply = reserveTotalSupply.add(reserveFee);\n unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee);\n emit ReserveFeeCaptured(reserveFee);\n }\n _currentAwardBalance = _currentAwardBalance.add(unaccountedPrizeBalance);\n\n emit AwardCaptured(unaccountedPrizeBalance);\n }\n\n return _currentAwardBalance;\n }\n\n function withdrawReserve(address to) external override onlyReserve returns (uint256) {\n\n uint256 amount = reserveTotalSupply;\n reserveTotalSupply = 0;\n uint256 redeemed = _redeem(amount);\n\n _token().safeTransfer(address(to), redeemed);\n\n emit ReserveWithdrawal(to, amount);\n\n return redeemed;\n }\n\n /// @notice Called by the prize strategy to award prizes.\n /// @dev The amount awarded must be less than the awardBalance()\n /// @param to The address of the winner that receives the award\n /// @param amount The amount of assets to be awarded\n /// @param controlledToken The address of the asset token being awarded\n function award(\n address to,\n uint256 amount,\n address controlledToken\n )\n external override\n onlyPrizeStrategy\n onlyControlledToken(controlledToken)\n {\n if (amount == 0) {\n return;\n }\n\n require(amount <= _currentAwardBalance, \"PrizePool/award-exceeds-avail\");\n _currentAwardBalance = _currentAwardBalance.sub(amount);\n\n _mint(to, amount, controlledToken, address(0));\n\n uint256 extraCredit = _calculateEarlyExitFeeNoCredit(controlledToken, amount);\n _accrueCredit(to, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(to), extraCredit);\n\n emit Awarded(to, controlledToken, amount);\n }\n\n /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens\n /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.\n /// @param to The address of the winner that receives the award\n /// @param amount The amount of external assets to be awarded\n /// @param externalToken The address of the external asset token being awarded\n function transferExternalERC20(\n address to,\n address externalToken,\n uint256 amount\n )\n external override\n onlyPrizeStrategy\n {\n if (_transferOut(to, externalToken, amount)) {\n emit TransferredExternalERC20(to, externalToken, amount);\n }\n }\n\n /// @notice Called by the Prize-Strategy to award external ERC20 prizes\n /// @dev Used to award any arbitrary tokens held by the Prize Pool\n /// @param to The address of the winner that receives the award\n /// @param amount The amount of external assets to be awarded\n /// @param externalToken The address of the external asset token being awarded\n function awardExternalERC20(\n address to,\n address externalToken,\n uint256 amount\n )\n external override\n onlyPrizeStrategy\n {\n if (_transferOut(to, externalToken, amount)) {\n emit AwardedExternalERC20(to, externalToken, amount);\n }\n }\n\n function _transferOut(\n address to,\n address externalToken,\n uint256 amount\n )\n internal\n returns (bool)\n {\n require(_canAwardExternal(externalToken), \"PrizePool/invalid-external-token\");\n\n if (amount == 0) {\n return false;\n }\n\n IERC20Upgradeable(externalToken).safeTransfer(to, amount);\n\n return true;\n }\n\n /// @notice Called to mint controlled tokens. Ensures that token listener callbacks are fired.\n /// @param to The user who is receiving the tokens\n /// @param amount The amount of tokens they are receiving\n /// @param controlledToken The token that is going to be minted\n /// @param referrer The user who referred the minting\n function _mint(address to, uint256 amount, address controlledToken, address referrer) internal {\n if (address(prizeStrategy) != address(0)) {\n prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer);\n }\n ControlledToken(controlledToken).controllerMint(to, amount);\n }\n\n /// @notice Called by the prize strategy to award external ERC721 prizes\n /// @dev Used to award any arbitrary NFTs held by the Prize Pool\n /// @param to The address of the winner that receives the award\n /// @param externalToken The address of the external NFT token being awarded\n /// @param tokenIds An array of NFT Token IDs to be transferred\n function awardExternalERC721(\n address to,\n address externalToken,\n uint256[] calldata tokenIds\n )\n external override\n onlyPrizeStrategy\n {\n require(_canAwardExternal(externalToken), \"PrizePool/invalid-external-token\");\n\n if (tokenIds.length == 0) {\n return;\n }\n\n for (uint256 i = 0; i < tokenIds.length; i++) {\n try IERC721Upgradeable(externalToken).safeTransferFrom(address(this), to, tokenIds[i]){\n\n }\n catch(bytes memory error){\n emit ErrorAwardingExternalERC721(error);\n }\n \n }\n\n emit AwardedExternalERC721(to, externalToken, tokenIds);\n }\n\n /// @notice Calculates the reserve portion of the given amount of funds. If there is no reserve address, the portion will be zero.\n /// @param amount The prize amount\n /// @return The size of the reserve portion of the prize\n function calculateReserveFee(uint256 amount) public view returns (uint256) {\n ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup());\n if (address(reserve) == address(0)) {\n return 0;\n }\n uint256 reserveRateMantissa = reserve.reserveRateMantissa(address(this));\n if (reserveRateMantissa == 0) {\n return 0;\n }\n return FixedPoint.multiplyUintByMantissa(amount, reserveRateMantissa);\n }\n\n /// @notice Calculates the early exit fee for the given amount\n /// @param from The user who is withdrawing\n /// @param controlledToken The type of collateral being withdrawn\n /// @param amount The amount of collateral to be withdrawn\n /// @return exitFee The exit fee\n /// @return burnedCredit The user's credit that was burned\n function calculateEarlyExitFee(\n address from,\n address controlledToken,\n uint256 amount\n )\n external override\n returns (\n uint256 exitFee,\n uint256 burnedCredit\n )\n {\n (exitFee, burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);\n }\n\n /// @dev Calculates the early exit fee for the given amount\n /// @param amount The amount of collateral to be withdrawn\n /// @return Exit fee\n function _calculateEarlyExitFeeNoCredit(address controlledToken, uint256 amount) internal view returns (uint256) {\n return _limitExitFee(\n amount,\n FixedPoint.multiplyUintByMantissa(amount, _tokenCreditPlans[controlledToken].creditLimitMantissa)\n );\n }\n\n /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit.\n /// @param _principal The principal amount on which interest is accruing\n /// @param _interest The amount of interest that must accrue\n /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.\n function estimateCreditAccrualTime(\n address _controlledToken,\n uint256 _principal,\n uint256 _interest\n )\n external override\n view\n returns (uint256 durationSeconds)\n {\n durationSeconds =_estimateCreditAccrualTime(\n _controlledToken,\n _principal,\n _interest\n );\n }\n\n /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit\n /// @param _principal The principal amount on which interest is accruing\n /// @param _interest The amount of interest that must accrue\n /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.\n function _estimateCreditAccrualTime(\n address _controlledToken,\n uint256 _principal,\n uint256 _interest\n )\n internal\n view\n returns (uint256 durationSeconds)\n {\n // interest = credit rate * principal * time\n // => time = interest / (credit rate * principal)\n uint256 accruedPerSecond = FixedPoint.multiplyUintByMantissa(_principal, _tokenCreditPlans[_controlledToken].creditRateMantissa);\n if (accruedPerSecond == 0) {\n return 0;\n }\n return _interest.div(accruedPerSecond);\n }\n\n /// @notice Burns a users credit.\n /// @param user The user whose credit should be burned\n /// @param credit The amount of credit to burn\n function _burnCredit(address user, address controlledToken, uint256 credit) internal {\n _tokenCreditBalances[controlledToken][user].balance = uint256(_tokenCreditBalances[controlledToken][user].balance).sub(credit).toUint128();\n\n emit CreditBurned(user, controlledToken, credit);\n }\n\n /// @notice Accrues ticket credit for a user assuming their current balance is the passed balance. May burn credit if they exceed their limit.\n /// @param user The user for whom to accrue credit\n /// @param controlledToken The controlled token whose balance we are checking\n /// @param controlledTokenBalance The balance to use for the user\n /// @param extra Additional credit to be added\n function _accrueCredit(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal {\n _updateCreditBalance(\n user,\n controlledToken,\n _calculateCreditBalance(user, controlledToken, controlledTokenBalance, extra)\n );\n }\n\n function _calculateCreditBalance(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal view returns (uint256) {\n uint256 newBalance;\n CreditBalance storage creditBalance = _tokenCreditBalances[controlledToken][user];\n if (!creditBalance.initialized) {\n newBalance = 0;\n } else {\n uint256 credit = _calculateAccruedCredit(user, controlledToken, controlledTokenBalance);\n newBalance = _applyCreditLimit(controlledToken, controlledTokenBalance, uint256(creditBalance.balance).add(credit).add(extra));\n }\n return newBalance;\n }\n\n function _updateCreditBalance(address user, address controlledToken, uint256 newBalance) internal {\n uint256 oldBalance = _tokenCreditBalances[controlledToken][user].balance;\n\n _tokenCreditBalances[controlledToken][user] = CreditBalance({\n balance: newBalance.toUint128(),\n timestamp: _currentTime().toUint32(),\n initialized: true\n });\n\n if (oldBalance < newBalance) {\n emit CreditMinted(user, controlledToken, newBalance.sub(oldBalance));\n } \n else if (newBalance < oldBalance) {\n emit CreditBurned(user, controlledToken, oldBalance.sub(newBalance));\n }\n }\n\n /// @notice Applies the credit limit to a credit balance. The balance cannot exceed the credit limit.\n /// @param controlledToken The controlled token that the user holds\n /// @param controlledTokenBalance The users ticket balance (used to calculate credit limit)\n /// @param creditBalance The new credit balance to be checked\n /// @return The users new credit balance. Will not exceed the credit limit.\n function _applyCreditLimit(address controlledToken, uint256 controlledTokenBalance, uint256 creditBalance) internal view returns (uint256) {\n uint256 creditLimit = FixedPoint.multiplyUintByMantissa(\n controlledTokenBalance,\n _tokenCreditPlans[controlledToken].creditLimitMantissa\n );\n if (creditBalance > creditLimit) {\n creditBalance = creditLimit;\n }\n\n return creditBalance;\n }\n\n /// @notice Calculates the accrued interest for a user\n /// @param user The user whose credit should be calculated.\n /// @param controlledToken The controlled token that the user holds\n /// @param controlledTokenBalance The user's current balance of the controlled tokens.\n /// @return The credit that has accrued since the last credit update.\n function _calculateAccruedCredit(address user, address controlledToken, uint256 controlledTokenBalance) internal view returns (uint256) {\n uint256 userTimestamp = _tokenCreditBalances[controlledToken][user].timestamp;\n\n if (!_tokenCreditBalances[controlledToken][user].initialized) {\n return 0;\n }\n\n uint256 deltaTime = _currentTime().sub(userTimestamp);\n uint256 deltaMantissa = deltaTime.mul(_tokenCreditPlans[controlledToken].creditRateMantissa);\n return FixedPoint.multiplyUintByMantissa(controlledTokenBalance, deltaMantissa);\n }\n\n /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit.\n /// @param user The user whose credit balance should be returned\n /// @return The balance of the users credit\n function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) {\n _accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0);\n return _tokenCreditBalances[controlledToken][user].balance;\n }\n\n /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether).\n /// @param _controlledToken The controlled token for whom to set the credit plan\n /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether).\n /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether).\n function setCreditPlanOf(\n address _controlledToken,\n uint128 _creditRateMantissa,\n uint128 _creditLimitMantissa\n )\n external override\n onlyControlledToken(_controlledToken)\n onlyOwner\n {\n _tokenCreditPlans[_controlledToken] = CreditPlan({\n creditLimitMantissa: _creditLimitMantissa,\n creditRateMantissa: _creditRateMantissa\n });\n\n emit CreditPlanSet(_controlledToken, _creditLimitMantissa, _creditRateMantissa);\n }\n\n /// @notice Returns the credit rate of a controlled token\n /// @param controlledToken The controlled token to retrieve the credit rates for\n /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee.\n /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second.\n function creditPlanOf(\n address controlledToken\n )\n external override\n view\n returns (\n uint128 creditLimitMantissa,\n uint128 creditRateMantissa\n )\n {\n creditLimitMantissa = _tokenCreditPlans[controlledToken].creditLimitMantissa;\n creditRateMantissa = _tokenCreditPlans[controlledToken].creditRateMantissa;\n }\n\n /// @notice Calculate the early exit for a user given a withdrawal amount. The user's credit is taken into account.\n /// @param from The user who is withdrawing\n /// @param controlledToken The token they are withdrawing\n /// @param amount The amount of funds they are withdrawing\n /// @return earlyExitFee The additional exit fee that should be charged.\n /// @return creditBurned The amount of credit that will be burned\n function _calculateEarlyExitFeeLessBurnedCredit(\n address from,\n address controlledToken,\n uint256 amount\n )\n internal\n returns (\n uint256 earlyExitFee,\n uint256 creditBurned\n )\n {\n uint256 controlledTokenBalance = IERC20Upgradeable(controlledToken).balanceOf(from);\n require(controlledTokenBalance >= amount, \"PrizePool/insuff-funds\");\n _accrueCredit(from, controlledToken, controlledTokenBalance, 0);\n /*\n The credit is used *last*. Always charge the fees up-front.\n\n How to calculate:\n\n Calculate their remaining exit fee. I.e. full exit fee of their balance less their credit.\n\n If the exit fee on their withdrawal is greater than the remaining exit fee, then they'll have to pay the difference.\n */\n\n // Determine available usable credit based on withdraw amount\n uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount));\n\n uint256 availableCredit;\n if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) {\n availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee);\n }\n\n // Determine amount of credit to burn and amount of fees required\n uint256 totalExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, amount);\n creditBurned = (availableCredit > totalExitFee) ? totalExitFee : availableCredit;\n earlyExitFee = totalExitFee.sub(creditBurned);\n }\n\n /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold\n /// @param _liquidityCap The new liquidity cap for the prize pool\n function setLiquidityCap(uint256 _liquidityCap) external override onlyOwner {\n _setLiquidityCap(_liquidityCap);\n }\n\n function _setLiquidityCap(uint256 _liquidityCap) internal {\n liquidityCap = _liquidityCap;\n emit LiquidityCapSet(_liquidityCap);\n }\n\n /// @notice Adds a new controlled token\n /// @param _controlledToken The controlled token to add.\n /// @param index The index to add the controlledToken\n function _addControlledToken(ControlledTokenInterface _controlledToken, uint256 index) internal {\n require(_controlledToken.controller() == this, \"PrizePool/token-ctrlr-mismatch\");\n \n _tokens[index] = _controlledToken;\n emit ControlledTokenAdded(_controlledToken);\n }\n\n /// @notice Sets the prize strategy of the prize pool. Only callable by the owner.\n /// @param _prizeStrategy The new prize strategy\n function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external override onlyOwner {\n _setPrizeStrategy(_prizeStrategy);\n }\n\n /// @notice Sets the prize strategy of the prize pool. Only callable by the owner.\n /// @param _prizeStrategy The new prize strategy\n function _setPrizeStrategy(TokenListenerInterface _prizeStrategy) internal {\n require(address(_prizeStrategy) != address(0), \"PrizePool/prizeStrategy-not-zero\");\n require(address(_prizeStrategy).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), \"PrizePool/prizeStrategy-invalid\");\n prizeStrategy = _prizeStrategy;\n\n emit PrizeStrategySet(address(_prizeStrategy));\n }\n\n /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship)\n /// @return An array of controlled token addresses\n function tokens() external override view returns (ControlledTokenInterface[] memory) {\n return _tokens;\n }\n\n /// @dev Gets the current time as represented by the current block\n /// @return The timestamp of the current block\n function _currentTime() internal virtual view returns (uint256) {\n return block.timestamp;\n }\n\n /// @notice The total of all controlled tokens\n /// @return The current total of all tokens\n function accountedBalance() external override view returns (uint256) {\n return _tokenTotalSupply();\n }\n\n /// @notice Delegate the votes for a Compound COMP-like token held by the prize pool\n /// @param compLike The COMP-like token held by the prize pool that should be delegated\n /// @param to The address to delegate to \n function compLikeDelegate(ICompLike compLike, address to) external onlyOwner {\n if (compLike.balanceOf(address(this)) > 0) {\n compLike.delegate(to);\n }\n }\n \n /// @notice Required for ERC721 safe token transfers from smart contracts.\n /// @param operator The address that acts on behalf of the owner\n /// @param from The current owner of the NFT\n /// @param tokenId The NFT to transfer\n /// @param data Additional data with no specified format, sent in call to `_to`.\n function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4){\n return IERC721ReceiverUpgradeable.onERC721Received.selector;\n }\n\n /// @notice The total of all controlled tokens\n /// @return The current total of all tokens\n function _tokenTotalSupply() internal view returns (uint256) {\n uint256 total = reserveTotalSupply;\n ControlledTokenInterface[] memory tokens = _tokens; // SLOAD \n uint256 tokensLength = tokens.length;\n \n for(uint256 i = 0; i < tokensLength; i++){\n total = total.add(IERC20Upgradeable(tokens[i]).totalSupply());\n }\n\n return total;\n }\n\n /// @dev Checks if the Prize Pool can receive liquidity based on the current cap\n /// @param _amount The amount of liquidity to be added to the Prize Pool\n /// @return True if the Prize Pool can receive the specified amount of liquidity\n function _canAddLiquidity(uint256 _amount) internal view returns (bool) {\n uint256 tokenTotalSupply = _tokenTotalSupply();\n return (tokenTotalSupply.add(_amount) <= liquidityCap);\n }\n\n /// @dev Checks if a specific token is controlled by the Prize Pool\n /// @param controlledToken The address of the token to check\n /// @return True if the token is a controlled token, false otherwise\n function _isControlled(ControlledTokenInterface controlledToken) internal view returns (bool) {\n ControlledTokenInterface[] memory tokens = _tokens; // SLOAD\n uint256 tokensLength = tokens.length;\n\n for(uint256 i = 0; i < tokensLength; i++) {\n if(tokens[i] == controlledToken) return true;\n }\n return false;\n }\n \n /// @dev Checks if a specific token is controlled by the Prize Pool\n /// @param controlledToken The address of the token to check\n /// @return True if the token is a controlled token, false otherwise\n function isControlled(ControlledTokenInterface controlledToken) external view returns (bool) {\n return _isControlled(controlledToken);\n }\n\n /// @notice Determines whether the passed token can be transferred out as an external award.\n /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The\n /// prize strategy should not be allowed to move those tokens.\n /// @param _externalToken The address of the token to check\n /// @return True if the token may be awarded, false otherwise\n function _canAwardExternal(address _externalToken) internal virtual view returns (bool);\n\n /// @notice Returns the ERC20 asset token used for deposits.\n /// @return The ERC20 asset token\n function _token() internal virtual view returns (IERC20Upgradeable);\n\n /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.\n /// @return The underlying balance of asset tokens\n function _balance() internal virtual returns (uint256);\n\n /// @notice Supplies asset tokens to the yield source.\n /// @param mintAmount The amount of asset tokens to be supplied\n function _supply(uint256 mintAmount) internal virtual;\n\n /// @notice Redeems asset tokens from the yield source.\n /// @param redeemAmount The amount of yield-bearing tokens to be redeemed\n /// @return The actual amount of tokens that were redeemed.\n function _redeem(uint256 redeemAmount) internal virtual returns (uint256);\n\n /// @dev Function modifier to ensure usage of tokens controlled by the Prize Pool\n /// @param controlledToken The address of the token to check\n modifier onlyControlledToken(address controlledToken) {\n require(_isControlled(ControlledTokenInterface(controlledToken)), \"PrizePool/unknown-token\");\n _;\n }\n\n /// @dev Function modifier to ensure caller is the prize-strategy\n modifier onlyPrizeStrategy() {\n require(_msgSender() == address(prizeStrategy), \"PrizePool/only-prizeStrategy\");\n _;\n }\n\n /// @dev Function modifier to ensure the deposit amount does not exceed the liquidity cap (if set)\n modifier canAddLiquidity(uint256 _amount) {\n require(_canAddLiquidity(_amount), \"PrizePool/exceeds-liquidity-cap\");\n _;\n }\n\n modifier onlyReserve() {\n ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup());\n require(address(reserve) == msg.sender, \"PrizePool/only-reserve\");\n _;\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/Initializable.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal initializer {\n __Context_init_unchained();\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal initializer {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n uint256[49] private __gap;\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value < 2**128, \"SafeCast: value doesn\\'t fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value < 2**64, \"SafeCast: value doesn\\'t fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value < 2**32, \"SafeCast: value doesn\\'t fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value < 2**16, \"SafeCast: value doesn\\'t fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value < 2**8, \"SafeCast: value doesn\\'t fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(value >= -2**127 && value < 2**127, \"SafeCast: value doesn\\'t fit in 128 bits\");\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(value >= -2**63 && value < 2**63, \"SafeCast: value doesn\\'t fit in 64 bits\");\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(value >= -2**31 && value < 2**31, \"SafeCast: value doesn\\'t fit in 32 bits\");\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(value >= -2**15 && value < 2**15, \"SafeCast: value doesn\\'t fit in 16 bits\");\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(value >= -2**7 && value < 2**7, \"SafeCast: value doesn\\'t fit in 8 bits\");\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n require(value < 2**255, \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\nimport \"../proxy/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal initializer {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal initializer {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n uint256[49] private __gap;\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\nimport \"../../introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.\n */\n function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Library used to query support of an interface declared via {IERC165}.\n *\n * Note that these functions return the actual result of the query: they do not\n * `revert` if an interface is not supported. It is up to the caller to decide\n * what to do in these cases.\n */\nlibrary ERC165CheckerUpgradeable {\n // As per the EIP-165 spec, no interface should ever match 0xffffffff\n bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;\n\n /*\n * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7\n */\n bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;\n\n /**\n * @dev Returns true if `account` supports the {IERC165} interface,\n */\n function supportsERC165(address account) internal view returns (bool) {\n // Any contract that implements ERC165 must explicitly indicate support of\n // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\n return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&\n !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);\n }\n\n /**\n * @dev Returns true if `account` supports the interface defined by\n * `interfaceId`. Support for {IERC165} itself is queried automatically.\n *\n * See {IERC165-supportsInterface}.\n */\n function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {\n // query support of both ERC165 as per the spec and support of _interfaceId\n return supportsERC165(account) &&\n _supportsERC165Interface(account, interfaceId);\n }\n\n /**\n * @dev Returns a boolean array where each value corresponds to the\n * interfaces passed in and whether they're supported or not. This allows\n * you to batch check interfaces for a contract where your expectation\n * is that some interfaces may not be supported.\n *\n * See {IERC165-supportsInterface}.\n *\n * _Available since v3.4._\n */\n function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {\n // an array of booleans corresponding to interfaceIds and whether they're supported or not\n bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);\n\n // query support of ERC165 itself\n if (supportsERC165(account)) {\n // query support of each interface in interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);\n }\n }\n\n return interfaceIdsSupported;\n }\n\n /**\n * @dev Returns true if `account` supports all the interfaces defined in\n * `interfaceIds`. Support for {IERC165} itself is queried automatically.\n *\n * Batch-querying can lead to gas savings by skipping repeated checks for\n * {IERC165} support.\n *\n * See {IERC165-supportsInterface}.\n */\n function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\n // query support of ERC165 itself\n if (!supportsERC165(account)) {\n return false;\n }\n\n // query support of each interface in _interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n if (!_supportsERC165Interface(account, interfaceIds[i])) {\n return false;\n }\n }\n\n // all interfaces supported\n return true;\n }\n\n /**\n * @notice Query if a contract implements an interface, does not check ERC165 support\n * @param account The address of the contract to query for support of an interface\n * @param interfaceId The interface identifier, as specified in ERC-165\n * @return true if the contract at account indicates support of the interface with\n * identifier interfaceId, false otherwise\n * @dev Assumes that account contains a contract that supports ERC165, otherwise\n * the behavior of this method is undefined. This precondition can be checked\n * with {supportsERC165}.\n * Interface identification is specified in ERC-165.\n */\n function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {\n // success determines whether the staticcall succeeded and result determines\n // whether the contract at account indicates support of _interfaceId\n (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);\n\n return (success && result);\n }\n\n /**\n * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw\n * @param account The address of the contract to query for support of an interface\n * @param interfaceId The interface identifier, as specified in ERC-165\n * @return success true if the STATICCALL succeeded, false otherwise\n * @return result true if the STATICCALL succeeded and the contract at account\n * indicates support of the interface with identifier interfaceId, false otherwise\n */\n function _callERC165SupportsInterface(address account, bytes4 interfaceId)\n private\n view\n returns (bool, bool)\n {\n bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);\n (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);\n if (result.length < 32) return (false, false);\n return (success, abi.decode(result, (bool)));\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./IERC20Upgradeable.sol\";\nimport \"../../math/SafeMathUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using SafeMathUpgradeable for uint256;\n using AddressUpgradeable for address;\n\n function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
|
|
},
|
|
"@pooltogether/fixed-point/contracts/FixedPoint.sol": {
|
|
"content": "/**\nCopyright 2020 PoolTogether Inc.\n\nThis file is part of PoolTogether.\n\nPoolTogether is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation under version 3 of the License.\n\nPoolTogether is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with PoolTogether. If not, see <https://www.gnu.org/licenses/>.\n*/\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol\";\n\n/**\n * @author Brendan Asselstine\n * @notice Provides basic fixed point math calculations.\n *\n * This library calculates integer fractions by scaling values by 1e18 then performing standard integer math.\n */\nlibrary FixedPoint {\n using OpenZeppelinSafeMath_V3_3_0 for uint256;\n\n // The scale to use for fixed point numbers. Same as Ether for simplicity.\n uint256 internal constant SCALE = 1e18;\n\n /**\n * Calculates a Fixed18 mantissa given the numerator and denominator\n *\n * The mantissa = (numerator * 1e18) / denominator\n *\n * @param numerator The mantissa numerator\n * @param denominator The mantissa denominator\n * @return The mantissa of the fraction\n */\n function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) {\n uint256 mantissa = numerator.mul(SCALE);\n mantissa = mantissa.div(denominator);\n return mantissa;\n }\n\n /**\n * Multiplies a Fixed18 number by an integer.\n *\n * @param b The whole integer to multiply\n * @param mantissa The Fixed18 number\n * @return An integer that is the result of multiplying the params.\n */\n function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) {\n uint256 result = mantissa.mul(b);\n result = result.div(SCALE);\n return result;\n }\n\n /**\n * Divides an integer by a fixed point 18 mantissa\n *\n * @param dividend The integer to divide\n * @param mantissa The fixed point 18 number to serve as the divisor\n * @return An integer that is the result of dividing an integer by a fixed point 18 mantissa\n */\n function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) {\n uint256 result = SCALE.mul(dividend);\n result = result.div(mantissa);\n return result;\n }\n}\n"
|
|
},
|
|
"contracts/external/compound/ICompLike.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface ICompLike is IERC20Upgradeable {\n function getCurrentVotes(address account) external view returns (uint96);\n function delegate(address delegatee) external;\n}\n"
|
|
},
|
|
"contracts/registry/RegistryInterface.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0 <0.7.0;\n\n/// @title Interface that allows a user to draw an address using an index\ninterface RegistryInterface {\n function lookup() external view returns (address);\n}\n"
|
|
},
|
|
"contracts/reserve/ReserveInterface.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0 <0.7.0;\n\n/// @title Interface that allows a user to draw an address using an index\ninterface ReserveInterface {\n function reserveRateMantissa(address prizePool) external view returns (uint256);\n}\n"
|
|
},
|
|
"contracts/token/TokenListenerInterface.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0 <0.7.0;\n\nimport \"@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol\";\n\n/// @title An interface that allows a contract to listen to token mint, transfer and burn events.\ninterface TokenListenerInterface is IERC165Upgradeable {\n /// @notice Called when tokens are minted.\n /// @param to The address of the receiver of the minted tokens.\n /// @param amount The amount of tokens being minted\n /// @param controlledToken The address of the token that is being minted\n /// @param referrer The address that referred the minting.\n function beforeTokenMint(address to, uint256 amount, address controlledToken, address referrer) external;\n\n /// @notice Called when tokens are transferred or burned.\n /// @param from The address of the sender of the token transfer\n /// @param to The address of the receiver of the token transfer. Will be the zero address if burning.\n /// @param amount The amount of tokens transferred\n /// @param controlledToken The address of the token that was transferred\n function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external;\n}\n"
|
|
},
|
|
"contracts/token/TokenListenerLibrary.sol": {
|
|
"content": "pragma solidity 0.6.12;\n\nlibrary TokenListenerLibrary {\n /*\n * bytes4(keccak256('beforeTokenMint(address,uint256,address,address)')) == 0x4d7f3db0\n * bytes4(keccak256('beforeTokenTransfer(address,address,uint256,address)')) == 0xb2210957\n *\n * => 0x4d7f3db0 ^ 0xb2210957 == 0xff5e34e7\n */\n bytes4 public constant ERC165_INTERFACE_ID_TOKEN_LISTENER = 0xff5e34e7;\n}"
|
|
},
|
|
"contracts/token/ControlledToken.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts-upgradeable/drafts/ERC20PermitUpgradeable.sol\";\n\nimport \"./TokenControllerInterface.sol\";\nimport \"./ControlledTokenInterface.sol\";\n\n/// @title Controlled ERC20 Token\n/// @notice ERC20 Tokens with a controller for minting & burning\ncontract ControlledToken is ERC20PermitUpgradeable, ControlledTokenInterface {\n\n /// @dev Emitted when an instance is initialized\n event Initialized(\n string _name,\n string _symbol,\n uint8 _decimals,\n TokenControllerInterface _controller\n );\n\n /// @notice Interface to the contract responsible for controlling mint/burn\n TokenControllerInterface public override controller;\n\n /// @notice Initializes the Controlled Token with Token Details and the Controller\n /// @param _name The name of the Token\n /// @param _symbol The symbol for the Token\n /// @param _decimals The number of decimals for the Token\n /// @param _controller Address of the Controller contract for minting & burning\n function initialize(\n string memory _name,\n string memory _symbol,\n uint8 _decimals,\n TokenControllerInterface _controller\n )\n public\n virtual\n initializer\n {\n require(address(_controller) != address(0), \"ControlledToken/controller-not-zero\");\n __ERC20_init(_name, _symbol);\n __ERC20Permit_init(\"PoolTogether ControlledToken\");\n controller = _controller;\n _setupDecimals(_decimals);\n\n emit Initialized(\n _name,\n _symbol,\n _decimals,\n _controller\n );\n }\n\n /// @notice Allows the controller to mint tokens for a user account\n /// @dev May be overridden to provide more granular control over minting\n /// @param _user Address of the receiver of the minted tokens\n /// @param _amount Amount of tokens to mint\n function controllerMint(address _user, uint256 _amount) external virtual override onlyController {\n _mint(_user, _amount);\n }\n\n /// @notice Allows the controller to burn tokens from a user account\n /// @dev May be overridden to provide more granular control over burning\n /// @param _user Address of the holder account to burn tokens from\n /// @param _amount Amount of tokens to burn\n function controllerBurn(address _user, uint256 _amount) external virtual override onlyController {\n _burn(_user, _amount);\n }\n\n /// @notice Allows an operator via the controller to burn tokens on behalf of a user account\n /// @dev May be overridden to provide more granular control over operator-burning\n /// @param _operator Address of the operator performing the burn action via the controller contract\n /// @param _user Address of the holder account to burn tokens from\n /// @param _amount Amount of tokens to burn\n function controllerBurnFrom(address _operator, address _user, uint256 _amount) external virtual override onlyController {\n if (_operator != _user) {\n uint256 decreasedAllowance = allowance(_user, _operator).sub(_amount, \"ControlledToken/exceeds-allowance\");\n _approve(_user, _operator, decreasedAllowance);\n }\n _burn(_user, _amount);\n }\n\n /// @dev Function modifier to ensure that the caller is the controller contract\n modifier onlyController {\n require(_msgSender() == address(controller), \"ControlledToken/only-controller\");\n _;\n }\n\n /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.\n /// This includes minting and burning.\n /// May be overridden to provide more granular control over operator-burning\n /// @param from Address of the account sending the tokens (address(0x0) on minting)\n /// @param to Address of the account receiving the tokens (address(0x0) on burning)\n /// @param amount Amount of tokens being transferred\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {\n controller.beforeTokenTransfer(from, to, amount);\n }\n}\n"
|
|
},
|
|
"contracts/token/TokenControllerInterface.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0 <0.7.0;\n\n/// @title Controlled ERC20 Token Interface\n/// @notice Required interface for Controlled ERC20 Tokens linked to a Prize Pool\n/// @dev Defines the spec required to be implemented by a Controlled ERC20 Token\ninterface TokenControllerInterface {\n\n /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.\n /// This includes minting and burning.\n /// @param from Address of the account sending the tokens (address(0x0) on minting)\n /// @param to Address of the account receiving the tokens (address(0x0) on burning)\n /// @param amount Amount of tokens being transferred\n function beforeTokenTransfer(address from, address to, uint256 amount) external;\n}\n"
|
|
},
|
|
"contracts/utils/MappedSinglyLinkedList.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\n/// @notice An efficient implementation of a singly linked list of addresses\n/// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list.\nlibrary MappedSinglyLinkedList {\n\n /// @notice The special value address used to denote the end of the list\n address public constant SENTINEL = address(0x1);\n\n /// @notice The data structure to use for the list.\n struct Mapping {\n uint256 count;\n\n mapping(address => address) addressMap;\n }\n\n /// @notice Initializes the list.\n /// @dev It is important that this is called so that the SENTINEL is correctly setup.\n function initialize(Mapping storage self) internal {\n require(self.count == 0, \"Already init\");\n self.addressMap[SENTINEL] = SENTINEL;\n }\n\n function start(Mapping storage self) internal view returns (address) {\n return self.addressMap[SENTINEL];\n }\n\n function next(Mapping storage self, address current) internal view returns (address) {\n return self.addressMap[current];\n }\n\n function end(Mapping storage) internal pure returns (address) {\n return SENTINEL;\n }\n\n function addAddresses(Mapping storage self, address[] memory addresses) internal {\n for (uint256 i = 0; i < addresses.length; i++) {\n addAddress(self, addresses[i]);\n }\n }\n\n /// @notice Adds an address to the front of the list.\n /// @param self The Mapping struct that this function is attached to\n /// @param newAddress The address to shift to the front of the list\n function addAddress(Mapping storage self, address newAddress) internal {\n require(newAddress != SENTINEL && newAddress != address(0), \"Invalid address\");\n require(self.addressMap[newAddress] == address(0), \"Already added\");\n self.addressMap[newAddress] = self.addressMap[SENTINEL];\n self.addressMap[SENTINEL] = newAddress;\n self.count = self.count + 1;\n }\n\n /// @notice Removes an address from the list\n /// @param self The Mapping struct that this function is attached to\n /// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start.\n /// @param addr The address to remove from the list.\n function removeAddress(Mapping storage self, address prevAddress, address addr) internal {\n require(addr != SENTINEL && addr != address(0), \"Invalid address\");\n require(self.addressMap[prevAddress] == addr, \"Invalid prevAddress\");\n self.addressMap[prevAddress] = self.addressMap[addr];\n delete self.addressMap[addr];\n self.count = self.count - 1;\n }\n\n /// @notice Determines whether the list contains the given address\n /// @param self The Mapping struct that this function is attached to\n /// @param addr The address to check\n /// @return True if the address is contained, false otherwise.\n function contains(Mapping storage self, address addr) internal view returns (bool) {\n return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0);\n }\n\n /// @notice Returns an address array of all the addresses in this list\n /// @dev Contains a for loop, so complexity is O(n) wrt the list size\n /// @param self The Mapping struct that this function is attached to\n /// @return An array of all the addresses\n function addressArray(Mapping storage self) internal view returns (address[] memory) {\n address[] memory array = new address[](self.count);\n uint256 count;\n address currentAddress = self.addressMap[SENTINEL];\n while (currentAddress != address(0) && currentAddress != SENTINEL) {\n array[count] = currentAddress;\n currentAddress = self.addressMap[currentAddress];\n count++;\n }\n return array;\n }\n\n /// @notice Removes every address from the list\n /// @param self The Mapping struct that this function is attached to\n function clearAll(Mapping storage self) internal {\n address currentAddress = self.addressMap[SENTINEL];\n while (currentAddress != address(0) && currentAddress != SENTINEL) {\n address nextAddress = self.addressMap[currentAddress];\n delete self.addressMap[currentAddress];\n currentAddress = nextAddress;\n }\n self.addressMap[SENTINEL] = SENTINEL;\n self.count = 0;\n }\n}\n"
|
|
},
|
|
"contracts/prize-pool/PrizePoolInterface.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\nimport \"../token/TokenListenerInterface.sol\";\nimport \"../token/ControlledTokenInterface.sol\";\n\n/// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool.\n/// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract.\n/// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens\ninterface PrizePoolInterface {\n\n /// @notice Deposit assets into the Prize Pool in exchange for tokens\n /// @param to The address receiving the newly minted tokens\n /// @param amount The amount of assets to deposit\n /// @param controlledToken The address of the type of token the user is minting\n /// @param referrer The referrer of the deposit\n function depositTo(\n address to,\n uint256 amount,\n address controlledToken,\n address referrer\n )\n external;\n\n /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit.\n /// @param from The address to redeem tokens from.\n /// @param amount The amount of tokens to redeem for assets.\n /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship)\n /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn.\n /// @return The actual exit fee paid\n function withdrawInstantlyFrom(\n address from,\n uint256 amount,\n address controlledToken,\n uint256 maximumExitFee\n ) external returns (uint256);\n\n\n function withdrawReserve(address to) external returns (uint256);\n\n /// @notice Returns the balance that is available to award.\n /// @dev captureAwardBalance() should be called first\n /// @return The total amount of assets to be awarded for the current prize\n function awardBalance() external view returns (uint256);\n\n /// @notice Captures any available interest as award balance.\n /// @dev This function also captures the reserve fees.\n /// @return The total amount of assets to be awarded for the current prize\n function captureAwardBalance() external returns (uint256);\n\n /// @notice Called by the prize strategy to award prizes.\n /// @dev The amount awarded must be less than the awardBalance()\n /// @param to The address of the winner that receives the award\n /// @param amount The amount of assets to be awarded\n /// @param controlledToken The address of the asset token being awarded\n function award(\n address to,\n uint256 amount,\n address controlledToken\n )\n external;\n\n /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens\n /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.\n /// @param to The address of the winner that receives the award\n /// @param amount The amount of external assets to be awarded\n /// @param externalToken The address of the external asset token being awarded\n function transferExternalERC20(\n address to,\n address externalToken,\n uint256 amount\n )\n external;\n\n /// @notice Called by the Prize-Strategy to award external ERC20 prizes\n /// @dev Used to award any arbitrary tokens held by the Prize Pool\n /// @param to The address of the winner that receives the award\n /// @param amount The amount of external assets to be awarded\n /// @param externalToken The address of the external asset token being awarded\n function awardExternalERC20(\n address to,\n address externalToken,\n uint256 amount\n )\n external;\n\n /// @notice Called by the prize strategy to award external ERC721 prizes\n /// @dev Used to award any arbitrary NFTs held by the Prize Pool\n /// @param to The address of the winner that receives the award\n /// @param externalToken The address of the external NFT token being awarded\n /// @param tokenIds An array of NFT Token IDs to be transferred\n function awardExternalERC721(\n address to,\n address externalToken,\n uint256[] calldata tokenIds\n )\n external;\n\n /// @notice Calculates the early exit fee for the given amount\n /// @param from The user who is withdrawing\n /// @param controlledToken The type of collateral being withdrawn\n /// @param amount The amount of collateral to be withdrawn\n /// @return exitFee The exit fee\n /// @return burnedCredit The user's credit that was burned\n function calculateEarlyExitFee(\n address from,\n address controlledToken,\n uint256 amount\n )\n external\n returns (\n uint256 exitFee,\n uint256 burnedCredit\n );\n\n /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit.\n /// @param _principal The principal amount on which interest is accruing\n /// @param _interest The amount of interest that must accrue\n /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.\n function estimateCreditAccrualTime(\n address _controlledToken,\n uint256 _principal,\n uint256 _interest\n )\n external\n view\n returns (uint256 durationSeconds);\n\n /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit.\n /// @param user The user whose credit balance should be returned\n /// @return The balance of the users credit\n function balanceOfCredit(address user, address controlledToken) external returns (uint256);\n\n /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether).\n /// @param _controlledToken The controlled token for whom to set the credit plan\n /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether).\n /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether).\n function setCreditPlanOf(\n address _controlledToken,\n uint128 _creditRateMantissa,\n uint128 _creditLimitMantissa\n )\n external;\n\n /// @notice Returns the credit rate of a controlled token\n /// @param controlledToken The controlled token to retrieve the credit rates for\n /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee.\n /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second.\n function creditPlanOf(\n address controlledToken\n )\n external\n view\n returns (\n uint128 creditLimitMantissa,\n uint128 creditRateMantissa\n );\n\n /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold\n /// @param _liquidityCap The new liquidity cap for the prize pool\n function setLiquidityCap(uint256 _liquidityCap) external;\n\n /// @notice Sets the prize strategy of the prize pool. Only callable by the owner.\n /// @param _prizeStrategy The new prize strategy. Must implement TokenListenerInterface\n function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external;\n\n /// @dev Returns the address of the underlying ERC20 asset\n /// @return The address of the asset\n function token() external view returns (address);\n\n /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship)\n /// @return An array of controlled token addresses\n function tokens() external view returns (ControlledTokenInterface[] memory);\n\n /// @notice The total of all controlled tokens\n /// @return The current total of all tokens\n function accountedBalance() external view returns (uint256);\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\nimport \"../proxy/Initializable.sol\";\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal initializer {\n __Context_init_unchained();\n }\n\n function __Context_init_unchained() internal initializer {\n }\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n uint256[50] private __gap;\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/proxy/Initializable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.4.24 <0.8.0;\n\nimport \"../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Modifier to protect an initializer function from being invoked twice.\n */\n modifier initializer() {\n require(_initializing || _isConstructor() || !_initialized, \"Initializable: contract is already initialized\");\n\n bool isTopLevelCall = !_initializing;\n if (isTopLevelCall) {\n _initializing = true;\n _initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n _initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function _isConstructor() private view returns (bool) {\n return !AddressUpgradeable.isContract(address(this));\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMathUpgradeable {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a % b;\n }\n}\n"
|
|
},
|
|
"@pooltogether/fixed-point/contracts/external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\n// NOTE: Copied from OpenZeppelin Contracts version 3.3.0\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary OpenZeppelinSafeMath_V3_3_0 {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/drafts/ERC20PermitUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.5 <0.8.0;\n\nimport \"../token/ERC20/ERC20Upgradeable.sol\";\nimport \"./IERC20PermitUpgradeable.sol\";\nimport \"../cryptography/ECDSAUpgradeable.sol\";\nimport \"../utils/CountersUpgradeable.sol\";\nimport \"./EIP712Upgradeable.sol\";\nimport \"../proxy/Initializable.sol\";\n\n/**\n * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * _Available since v3.4._\n */\nabstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {\n using CountersUpgradeable for CountersUpgradeable.Counter;\n\n mapping (address => CountersUpgradeable.Counter) private _nonces;\n\n // solhint-disable-next-line var-name-mixedcase\n bytes32 private _PERMIT_TYPEHASH;\n\n /**\n * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n *\n * It's a good idea to use the same `name` that is defined as the ERC20 token name.\n */\n function __ERC20Permit_init(string memory name) internal initializer {\n __Context_init_unchained();\n __EIP712_init_unchained(name, \"1\");\n __ERC20Permit_init_unchained(name);\n }\n\n function __ERC20Permit_init_unchained(string memory name) internal initializer {\n _PERMIT_TYPEHASH = keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n }\n\n /**\n * @dev See {IERC20Permit-permit}.\n */\n function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {\n // solhint-disable-next-line not-rely-on-time\n require(block.timestamp <= deadline, \"ERC20Permit: expired deadline\");\n\n bytes32 structHash = keccak256(\n abi.encode(\n _PERMIT_TYPEHASH,\n owner,\n spender,\n value,\n _nonces[owner].current(),\n deadline\n )\n );\n\n bytes32 hash = _hashTypedDataV4(structHash);\n\n address signer = ECDSAUpgradeable.recover(hash, v, r, s);\n require(signer == owner, \"ERC20Permit: invalid signature\");\n\n _nonces[owner].increment();\n _approve(owner, spender, value);\n }\n\n /**\n * @dev See {IERC20Permit-nonces}.\n */\n function nonces(address owner) public view override returns (uint256) {\n return _nonces[owner].current();\n }\n\n /**\n * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view override returns (bytes32) {\n return _domainSeparatorV4();\n }\n uint256[49] private __gap;\n}\n"
|
|
},
|
|
"contracts/token/ControlledTokenInterface.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"./TokenControllerInterface.sol\";\n\n/// @title Controlled ERC20 Token\n/// @notice ERC20 Tokens with a controller for minting & burning\ninterface ControlledTokenInterface is IERC20Upgradeable {\n\n /// @notice Interface to the contract responsible for controlling mint/burn\n function controller() external view returns (TokenControllerInterface);\n\n /// @notice Allows the controller to mint tokens for a user account\n /// @dev May be overridden to provide more granular control over minting\n /// @param _user Address of the receiver of the minted tokens\n /// @param _amount Amount of tokens to mint\n function controllerMint(address _user, uint256 _amount) external;\n\n /// @notice Allows the controller to burn tokens from a user account\n /// @dev May be overridden to provide more granular control over burning\n /// @param _user Address of the holder account to burn tokens from\n /// @param _amount Amount of tokens to burn\n function controllerBurn(address _user, uint256 _amount) external;\n\n /// @notice Allows an operator via the controller to burn tokens on behalf of a user account\n /// @dev May be overridden to provide more granular control over operator-burning\n /// @param _operator Address of the operator performing the burn action via the controller contract\n /// @param _user Address of the holder account to burn tokens from\n /// @param _amount Amount of tokens to burn\n function controllerBurnFrom(address _operator, address _user, uint256 _amount) external;\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"./IERC20Upgradeable.sol\";\nimport \"../../math/SafeMathUpgradeable.sol\";\nimport \"../../proxy/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {\n using SafeMathUpgradeable for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n * a default value of 18.\n *\n * To select a different value for {decimals}, use {_setupDecimals}.\n *\n * All three of these values are immutable: they can only be set once during\n * construction.\n */\n function __ERC20_init(string memory name_, string memory symbol_) internal initializer {\n __Context_init_unchained();\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {\n _name = name_;\n _symbol = symbol_;\n _decimals = 18;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n * called.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return _decimals;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Sets {decimals} to a value other than the default one of 18.\n *\n * WARNING: This function should only be called from the constructor. Most\n * applications that interact with token contracts will not expect\n * {decimals} to ever change, and may work incorrectly if it does.\n */\n function _setupDecimals(uint8 decimals_) internal virtual {\n _decimals = decimals_;\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be to transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n uint256[44] private __gap;\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/drafts/IERC20PermitUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n /**\n * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,\n * given `owner`'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n // Check the signature length\n if (signature.length != 65) {\n revert(\"ECDSA: invalid signature length\");\n }\n\n // Divide the signature in r, s and v variables\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n // solhint-disable-next-line no-inline-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n\n return recover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, \"ECDSA: invalid signature 's' value\");\n require(v == 27 || v == 28, \"ECDSA: invalid signature 'v' value\");\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n require(signer != address(0), \"ECDSA: invalid signature\");\n\n return signer;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * replicates the behavior of the\n * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]\n * JSON-RPC method.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../math/SafeMathUpgradeable.sol\";\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}\n * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never\n * directly accessed.\n */\nlibrary CountersUpgradeable {\n using SafeMathUpgradeable for uint256;\n\n struct Counter {\n // This variable should never be directly accessed by users of the library: interactions must be restricted to\n // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n // this feature: see https://github.com/ethereum/solidity/issues/4637\n uint256 _value; // default: 0\n }\n\n function current(Counter storage counter) internal view returns (uint256) {\n return counter._value;\n }\n\n function increment(Counter storage counter) internal {\n // The {SafeMath} overflow check can be skipped here, see the comment at the top\n counter._value += 1;\n }\n\n function decrement(Counter storage counter) internal {\n counter._value = counter._value.sub(1);\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts-upgradeable/drafts/EIP712Upgradeable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\nimport \"../proxy/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal initializer {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal initializer {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {\n return keccak256(\n abi.encode(\n typeHash,\n name,\n version,\n _getChainId(),\n address(this)\n )\n );\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", _domainSeparatorV4(), structHash));\n }\n\n function _getChainId() private view returns (uint256 chainId) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n // solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n uint256[50] private __gap;\n}\n"
|
|
}
|
|
},
|
|
"settings": {
|
|
"optimizer": {
|
|
"enabled": true,
|
|
"runs": 200
|
|
},
|
|
"evmVersion": "istanbul",
|
|
"outputSelection": {
|
|
"*": {
|
|
"*": [
|
|
"evm.bytecode",
|
|
"evm.deployedBytecode",
|
|
"abi"
|
|
]
|
|
}
|
|
},
|
|
"metadata": {
|
|
"useLiteralContent": true
|
|
},
|
|
"libraries": {}
|
|
}
|
|
} |