file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/41/0xBEfF7c8A5B21caC0743A6DdCd22D04D281147028/sources/contracts/eip712/ERC721_712_DailyTelos.sol
Verifies the signature for a given NFTVoucher, returning the address of the signer. Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs. voucher An NFTVoucher describing an unminted NFT.
function _verify(NFTVoucher calldata voucher, bytes memory signature) internal view returns (address) { bytes32 digest = _hash(voucher); return ECDSA.recover(digest, signature); }
16,378,125
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; contract BondedVault is Ownable { address public authorisedSender; bool public collateralIsEth; ERC20Mintable public collateralToken; bool public isFrozen; event LogCollateralSend( uint amount, address indexed account ); event LogCollateralTypeChanged( bool isEth, address indexed account ); event LogEthDonated( uint amount, address indexed account ); event LogAuthorisedSenderChanged( address indexed newSender, address oldSender, address owner ); event LogVaultFrozen( address indexed owner, bool isFrozen ); modifier onlyAuthorisedSender() { require(msg.sender == authorisedSender, "Non-authorised sender"); _; } modifier onlyUnfrozen() { require(!isFrozen, "Vault is currently frozen"); _; } /** * @dev Send the underlying collateral to a specific address * @notice This function will send ETH or another ERC20 depending on the value of collateralIsEth. * @param _amount The amount of collateral to be transfered. * @param _account The address of the user to awarded. */ function sendCollateral(uint _amount, address payable _account) public onlyAuthorisedSender onlyUnfrozen { if (collateralIsEth) { _account.transfer(_amount); } else { collateralToken.transfer(_account, _amount); } emit LogCollateralSend(_amount, _account); } /** * @dev Set the underlying asset type for collateral * @notice By default this is set to non ETH (i.e. ERC20). * @param _collateralIsEth A bool value to determine if ETH is the collateral underlying the curve */ function setCollateralToEth(bool _collateralIsEth) public onlyOwner { collateralIsEth = _collateralIsEth; emit LogCollateralTypeChanged(_collateralIsEth, msg.sender); } /** * @dev Fallback function to accept direct ETH transfers as free donations to the bonding curve. * @notice Does not accept funds when vault is frozen. */ function () external onlyUnfrozen payable { emit LogEthDonated(msg.value, msg.sender); } /** * @dev Set the authorisedSender address. * @notice The authorisedSender is able to send collateral to an address. Ideally the authorisedSender * should be another contract such as the CommunityRegister. * @param _authorisedSender The address of the new authorisedSender. */ function setAuthorisedSender(address _authorisedSender) public onlyOwner { address oldSender = authorisedSender; authorisedSender = _authorisedSender; emit LogAuthorisedSenderChanged(_authorisedSender, oldSender, msg.sender); } /** * @dev Sets or unsets the vault in a frozen state, where no transfers are possible. * @param _isFrozen Whether the vault should be frozen or not. */ function setFreeze(bool _isFrozen) public onlyOwner { isFrozen = _isFrozen; emit LogVaultFrozen(msg.sender, isFrozen); } }
Set the authorisedSender address. The authorisedSender is able to send collateral to an address. Ideally the authorisedSender should be another contract such as the CommunityRegister. _authorisedSender The address of the new authorisedSender./
function setAuthorisedSender(address _authorisedSender) public onlyOwner { address oldSender = authorisedSender; authorisedSender = _authorisedSender; emit LogAuthorisedSenderChanged(_authorisedSender, oldSender, msg.sender); }
13,045,525
./full_match/5/0xA225bd6B70Fcc0738350d4EE038A85a71532149F/sources/contracts/MafiaNuts.sol
get tokenURI for a specific token. If collection is not revealed, return the defaultURI
function tokenURI(uint256 _tokenId) public view override returns (string memory){ require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); return isRevealed ? string(abi.encodePacked( baseTokenURI, _tokenId.toString() )) : defaultURI; }
1,870,574
./partial_match/1/0x6D0B05ef27C5D5A0783e86F6056B531616284D14/sources/contracts/RadbroWebringV2.sol
Set the address of the Randomness contract.
function setRandProvider(address _randProvider) external onlyOperator { randProvider = IRandomness(_randProvider); }
3,621,249
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol //Copyright 2020 Compound Labs, Inc. //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: //1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. //2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. //3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ComptrollerStorage.sol"; import "./IComptroller.sol"; import "../libs/ErrorReporter.sol"; import "../libs/Exponential.sol"; import "../token/IPToken.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../farm/PiggyDistribution.sol"; //PIGGY-MODIFY: Modified some methods and fields according to WePiggy's business logic contract Comptroller is ComptrollerStorage, IComptroller, ComptrollerErrorReporter, Exponential, OwnableUpgradeable { // @notice Emitted when an admin supports a market event MarketListed(IPToken pToken); // @notice Emitted when an account enters a market event MarketEntered(IPToken pToken, address account); // @notice Emitted when an account exits a market event MarketExited(IPToken pToken, address account); // @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); // @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(IPToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); // @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); // @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); // @notice Emitted when price oracle is changed event NewPriceOracle(IPriceOracle oldPriceOracle, IPriceOracle newPriceOracle); // @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); // @notice Emitted when an action is paused on a market event ActionPaused(IPToken pToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a pToken is changed event NewBorrowCap(IPToken indexed pToken, uint newBorrowCap); event NewPiggyDistribution(IPiggyDistribution oldPiggyDistribution, IPiggyDistribution newPiggyDistribution); /// @notice Emitted when mint cap for a pToken is changed event NewMintCap(IPToken indexed pToken, uint newMintCap); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // for distribute wpc IPiggyDistribution public piggyDistribution; mapping(address => uint256) public mintCaps; function initialize() public initializer { //setting the msg.sender as the initial owner. super.__Ownable_init(); } /*** Assets You Are In ***/ function enterMarkets(address[] memory pTokens) public override(IComptroller) returns (uint[] memory) { uint len = pTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { IPToken pToken = IPToken(pTokens[i]); results[i] = uint(addToMarketInternal(pToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param pToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(IPToken pToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(pToken)]; // market is not listed, cannot join if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } // already joined if (marketToJoin.accountMembership[borrower] == true) { return Error.NO_ERROR; } // no space, cannot join if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; } marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(pToken); emit MarketEntered(pToken, borrower); return Error.NO_ERROR; } function exitMarket(address pTokenAddress) external override(IComptroller) returns (uint) { IPToken pToken = IPToken(pTokenAddress); // Get sender tokensHeld and amountOwed underlying from the pToken (uint oErr, uint tokensHeld, uint amountOwed,) = pToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // Fail if the sender has a borrow balance if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } // Fail if the sender is not permitted to redeem all of their tokens uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(pToken)]; // Return true if the sender is not already ‘in’ the market if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } // Set pToken account membership to false delete marketToExit.accountMembership[msg.sender]; // Delete pToken from the account’s list of assets // load into memory for faster iteration IPToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == pToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 IPToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(pToken, msg.sender); return uint(Error.NO_ERROR); } /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (IPToken[] memory) { IPToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param pToken The pToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, IPToken pToken) external view returns (bool) { return markets[address(pToken)].accountMembership[account]; } /*** Policy Hooks ***/ function mintAllowed(address pToken, address minter, uint mintAmount) external override(IComptroller) returns (uint){ // Pausing is a very serious situation - we revert to sound the alarms require(!pTokenMintGuardianPaused[pToken], "mint is paused"); //Shh - currently unused. It's written here to eliminate compile-time alarms. minter; mintAmount; if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } uint mintCap = mintCaps[pToken]; if (mintCap != 0) { uint totalSupply = IPToken(pToken).totalSupply(); uint exchangeRate = IPToken(pToken).exchangeRateStored(); (MathError mErr, uint balance) = mulScalarTruncate(Exp({mantissa : exchangeRate}), totalSupply); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); (MathError mathErr, uint nextTotalMints) = addUInt(balance, mintAmount); require(mathErr == MathError.NO_ERROR, "total mint amount overflow"); require(nextTotalMints < mintCap, "market mint cap reached"); } if (distributeWpcPaused == false) { piggyDistribution.distributeMintWpc(pToken, minter, false); } return uint(Error.NO_ERROR); } function mintVerify(address pToken, address minter, uint mintAmount, uint mintTokens) external override(IComptroller) { //Shh - currently unused. It's written here to eliminate compile-time alarms. pToken; minter; mintAmount; mintTokens; } function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override(IComptroller) returns (uint){ uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } if (distributeWpcPaused == false) { piggyDistribution.distributeRedeemWpc(pToken, redeemer, false); } return uint(Error.NO_ERROR); } /** * PIGGY-MODIFY: * @notice Checks if the account should be allowed to redeem tokens in the given market * @param pToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of pTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[pToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, IPToken(pToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override(IComptroller) { //Shh - currently unused. It's written here to eliminate compile-time alarms. pToken; redeemer; redeemAmount; redeemTokens; } function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override(IComptroller) returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!pTokenBorrowGuardianPaused[pToken], "borrow is paused"); if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[pToken].accountMembership[borrower]) { // only pTokens may call borrowAllowed if borrower not in market require(msg.sender == pToken, "sender must be pToken"); // attempt to add borrower to the market Error err = addToMarketInternal(IPToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[pToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(IPToken(pToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[pToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = IPToken(pToken).totalBorrows(); (MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount); require(mathErr == MathError.NO_ERROR, "total borrows overflow"); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, IPToken(pToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } //distribute wpc if (distributeWpcPaused == false) { piggyDistribution.distributeBorrowWpc(pToken, borrower, false); } return uint(Error.NO_ERROR); } function borrowVerify(address pToken, address borrower, uint borrowAmount) external override(IComptroller) { //Shh - currently unused. It's written here to eliminate compile-time alarms. pToken; borrower; borrowAmount; } function repayBorrowAllowed(address pToken, address payer, address borrower, uint repayAmount) external override(IComptroller) returns (uint) { if (!markets[pToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Shh - currently unused. It's written here to eliminate compile-time alarms. payer; borrower; repayAmount; //distribute wpc if (distributeWpcPaused == false) { piggyDistribution.distributeRepayBorrowWpc(pToken, borrower, false); } return uint(Error.NO_ERROR); } function repayBorrowVerify(address pToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external override(IComptroller) { // Shh - currently unused. It's written here to eliminate compile-time alarms. pToken; payer; borrower; repayAmount; borrowerIndex; } function liquidateBorrowAllowed( address pTokenBorrowed, address pTokenCollateral, address liquidator, address borrower, uint repayAmount ) external override(IComptroller) returns (uint){ // Shh - currently unused. It's written here to eliminate compile-time alarms. liquidator; if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = IPToken(pTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } function liquidateBorrowVerify( address pTokenBorrowed, address pTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens ) external override(IComptroller) { // Shh - currently unused. It's written here to eliminate compile-time alarms. pTokenBorrowed; pTokenCollateral; liquidator; borrower; repayAmount; seizeTokens; } function seizeAllowed( address pTokenCollateral, address pTokenBorrowed, address liquidator, address borrower, uint seizeTokens ) external override(IComptroller) returns (uint){ // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused. It's written here to eliminate compile-time alarms. seizeTokens; if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (IPToken(pTokenCollateral).comptroller() != IPToken(pTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } //distribute wpc if (distributeWpcPaused == false) { piggyDistribution.distributeSeizeWpc(pTokenCollateral, borrower, liquidator, false); } return uint(Error.NO_ERROR); } function seizeVerify( address pTokenCollateral, address pTokenBorrowed, address liquidator, address borrower, uint seizeTokens ) external override(IComptroller) { // Shh - currently unused. It's written here to eliminate compile-time alarms. pTokenCollateral; pTokenBorrowed; liquidator; borrower; seizeTokens; } function transferAllowed( address pToken, address src, address dst, uint transferTokens ) external override(IComptroller) returns (uint){ // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(pToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } //distribute wpc if (distributeWpcPaused == false) { piggyDistribution.distributeTransferWpc(pToken, src, dst, false); } return uint(Error.NO_ERROR); } function transferVerify( address pToken, address src, address dst, uint transferTokens ) external override(IComptroller) { // Shh - currently unused. It's written here to eliminate compile-time alarms. pToken; src; dst; transferTokens; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `pTokenBalance` is the number of pTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint pTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, IPToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, IPToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param pTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address pTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, IPToken(pTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param account The account to determine liquidity for * @param pTokenModify The market to hypothetically redeem/borrow in * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, IPToken pTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; uint oErr; MathError mErr; // For each asset the account is in IPToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { IPToken asset = assets[i]; // Read the balances and exchange rate from the pToken (oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> usd (normalized price value) // pTokenPrice = oraclePrice * exchangeRate (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * pTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with pTokenModify if (asset == pTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } function liquidateCalculateSeizeTokens( address pTokenBorrowed, address pTokenCollateral, uint actualRepayAmount ) external override(IComptroller) view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(IPToken(pTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(IPToken(pTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) * * Note: reverts on error */ uint exchangeRateMantissa = IPToken(pTokenCollateral).exchangeRateStored(); uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(IPriceOracle newOracle) public onlyOwner returns (uint) { IPriceOracle oldOracle = oracle; oracle = newOracle; emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external onlyOwner returns (uint) { Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param pToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(IPToken pToken, uint newCollateralFactorMantissa) external onlyOwner returns (uint) { Market storage market = markets[address(pToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa}); Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external onlyOwner returns (uint) { uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyOwner returns (uint) { // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param pToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(IPToken pToken) external onlyOwner returns (uint) { if (markets[address(pToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } markets[address(pToken)] = Market({isListed : true, isMinted : false, collateralFactorMantissa : 0}); _addMarketInternal(address(pToken)); emit MarketListed(pToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address pToken) internal onlyOwner { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != IPToken(pToken), "market already added"); } allMarkets.push(IPToken(pToken)); } /** * @notice Set the given borrow caps for the given pToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param pTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(IPToken[] calldata pTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == owner(), "only owner can set borrow caps"); uint numMarkets = pTokens.length; uint numBorrowCaps = newBorrowCaps.length; for (uint i = 0; i < numMarkets; i++) { borrowCaps[address(pTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(pTokens[i], newBorrowCaps[i]); } } function _setMintPaused(IPToken pToken, bool state) public onlyOwner returns (bool) { require(markets[address(pToken)].isListed, "cannot pause a market that is not listed"); pTokenMintGuardianPaused[address(pToken)] = state; emit ActionPaused(pToken, "Mint", state); return state; } function _setBorrowPaused(IPToken pToken, bool state) public onlyOwner returns (bool) { require(markets[address(pToken)].isListed, "cannot pause a market that is not listed"); pTokenBorrowGuardianPaused[address(pToken)] = state; emit ActionPaused(pToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public onlyOwner returns (bool) { transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public onlyOwner returns (bool) { seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _setDistributeWpcPaused(bool state) public onlyOwner returns (bool) { distributeWpcPaused = state; emit ActionPaused("DistributeWpc", state); return state; } /** * @notice Sets a new price piggyDistribution for the comptroller * @dev Admin function to set a new piggy distribution * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) { IPiggyDistribution oldPiggyDistribution = piggyDistribution; piggyDistribution = newPiggyDistribution; emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution); return uint(Error.NO_ERROR); } function getAllMarkets() public view returns (IPToken[] memory){ return allMarkets; } function isMarketMinted(address pToken) public view returns (bool){ return markets[pToken].isMinted; } function isMarketListed(address pToken) public view returns (bool){ return markets[pToken].isListed; } function _setMarketMinted(address pToken, bool status) public { require(msg.sender == address(piggyDistribution) || msg.sender == owner(), "only PiggyDistribution or owner can update"); markets[pToken].isMinted = status; } function _setMarketMintCaps(IPToken[] calldata pTokens, uint[] calldata newMintCaps) external onlyOwner { uint numMarkets = pTokens.length; uint numMintCaps = newMintCaps.length; for (uint i = 0; i < numMarkets; i++) { mintCaps[address(pTokens[i])] = newMintCaps[i]; emit NewBorrowCap(pTokens[i], newMintCaps[i]); } } }
hypothetical account shortfall below collateral requirements)/
function getHypotheticalAccountLiquidity( address account, address pTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, IPToken(pTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); }
5,421,800
./full_match/1/0xfbB3742628e8D19E0E2d7D8dde208821C09dE960/sources/src/policies/BoostedLiquidity/interfaces/IBalancer.sol
Define Vault Interface
interface IVault { function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; function getPoolTokens( bytes32 poolId ) external view returns (address[] memory, uint256[] memory, uint256); }
4,916,287
pragma solidity ^0.5.8; import "browser/ERC20.sol"; contract ZUTtoken is ERC20 { // Data of the Token uint256 private _totalSupply; string public name; string public symbol; uint8 public decimals; event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; constructor() public { _totalSupply = 1000; name = "ZUTtoken"; symbol = "ZUTtkn"; decimals = 0; _balances[msg.sender] = totalSupply(); emit Transfer(address(0), msg.sender, totalSupply()); } // total amount of tokens which can be spent, when this limit will be reached, the smart contract will refuse to create new tokens function totalSupply() public view returns (uint256) { return _totalSupply; } // returns how many tokens specified address has function balanceOf(address _owner) public view returns (uint256) { return _balances[_owner]; } // takes amount of tokens from msg.sender and send them to recipient function transfer(address recipient, uint256 amount) public returns (bool) { require( msg.sender != address(0), "ERC20: transfer from the zero address" ); require(recipient != address(0), "ERC20: transfer to the zero address"); require( _balances[msg.sender] >= amount, "ERC20: amount exceeds balance" ); require(amount > 0, "ERC20: amount is zero or lower"); _balances[recipient] += amount; _balances[msg.sender] -= amount; emit Transfer(msg.sender, recipient, amount); return true; } // returns the amount of tokens with which spender can still withdraw from owner. function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } // approved spender is able to withdraw his balance so much as he want, but not more that amount function approve(address spender, uint256 amount) public returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // transfer tokens from sender and send them to recipient function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { require(_balances[sender] >= amount, "ERC20: amount exceeds balance"); require( _allowances[sender][msg.sender] >= amount, "ERC20: amount exceeds allowance" ); require(amount > 0, "ERC20: amount is zero or lower"); _balances[recipient] += amount; _balances[sender] -= amount; _allowances[sender][msg.sender] -= amount; emit Transfer(sender, recipient, amount); return true; } }
transfer tokens from sender and send them to recipient
function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { require(_balances[sender] >= amount, "ERC20: amount exceeds balance"); require( _allowances[sender][msg.sender] >= amount, "ERC20: amount exceeds allowance" ); require(amount > 0, "ERC20: amount is zero or lower"); _balances[recipient] += amount; _balances[sender] -= amount; _allowances[sender][msg.sender] -= amount; emit Transfer(sender, recipient, amount); return true; }
6,359,743
pragma solidity ^0.4.21; contract RetirementFundChallenge { uint256 startBalance; address owner = msg.sender; address beneficiary; uint256 expiration = now + 10 years; function RetirementFundChallenge(address player) public payable { require(msg.value == 1 ether); beneficiary = player; startBalance = msg.value; } function isComplete() public view returns (bool) { return address(this).balance == 0; } function withdraw() public { require(msg.sender == owner); if (now < expiration) { // early withdrawal incurs a 10% penalty msg.sender.transfer((address(this).balance * 9) / 10); } else { msg.sender.transfer(address(this).balance); } } function collectPenalty() public { require(msg.sender == beneficiary); uint256 withdrawn = startBalance - address(this).balance; // an early withdrawal occurred require(withdrawn > 0); // penalty is what's left msg.sender.transfer(address(this).balance); } }
early withdrawal incurs a 10% penalty
function withdraw() public { require(msg.sender == owner); if (now < expiration) { msg.sender.transfer((address(this).balance * 9) / 10); msg.sender.transfer(address(this).balance); } }
13,040,794
./partial_match/62320/0xd536b521b542D05533b0AC8fA3018aBe9e03DE1d/sources/redstone-oracles-monorepo-789f66c/packages/on-chain-relayer/contracts/custom-integrations/mento/linkedlists/SortedLinkedList.sol
Inserts an element at the tail of the doubly linked list. list A storage pointer to the underlying list. key The key of the element to insert./
function push(List storage list, bytes32 key) internal { insert(list, key, 0, bytes32(0), list.list.tail); }
11,034,360
./full_match/100/0x7BD4FaE40Dce40CC61E3e5E7E85aa0Fc403297fD/sources/contracts/OrbisReputation.sol
Private: Calls the Orbis contract to remove the old admin and update the new one _oldAdmin: Address of the previous admin to remove _newAdmin: Address of the new admin to update/
function _replaceAdmin(address _oldAdmin, address _newAdmin) private { require (IOrbis(orbisContract).isAdmin(communityID, _oldAdmin), "The admin to remove is not an admin of this community."); IOrbis(orbisContract).replaceAdmin(communityID, _oldAdmin, _newAdmin); }
14,265,257
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iAbs_BaseCrossDomainMessenger } from "../../../iOVM/bridge/messaging/iAbs_BaseCrossDomainMessenger.sol"; /* Library Imports */ import { Lib_ReentrancyGuard } from "../../../libraries/utils/Lib_ReentrancyGuard.sol"; /** * @title Abs_BaseCrossDomainMessenger * @dev The Base Cross Domain Messenger is an abstract contract providing the interface and common functionality used in the * L1 and L2 Cross Domain Messengers. It can also serve as a template for developers wishing to implement a custom bridge * contract to suit their needs. * * Compiler used: defined by child contract * Runtime target: defined by child contract */ abstract contract Abs_BaseCrossDomainMessenger is iAbs_BaseCrossDomainMessenger, Lib_ReentrancyGuard { /************** * Constants * **************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; mapping (bytes32 => bool) public sentMessages; uint256 public messageNonce; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /******************** * Public Functions * ********************/ constructor() Lib_ReentrancyGuard() {} function xDomainMessageSender() public override view returns (address) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, msg.sender, _message, messageNonce ); messageNonce += 1; sentMessages[keccak256(xDomainCalldata)] = true; _sendXDomainMessage(xDomainCalldata, _gasLimit); emit SentMessage(xDomainCalldata); } /********************** * Internal Functions * **********************/ /** * Generates the correct cross domain calldata for a message. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @return ABI encoded cross domain calldata. */ function _getXDomainCalldata( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "relayMessage(address,address,bytes,uint256)", _target, _sender, _message, _messageNonce ); } /** * Sends a cross domain message. * param // Message to send. * param // Gas limit for the provided message. */ function _sendXDomainMessage( bytes memory, // _message, uint256 // _gasLimit ) virtual internal { revert("Implement me in child contracts!"); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol"; import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_ReentrancyGuard } from "../../../libraries/utils/Lib_ReentrancyGuard.sol"; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_CanonicalTransactionChain } from "../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol"; /* Contract Imports */ import { Abs_BaseCrossDomainMessenger } from "./Abs_BaseCrossDomainMessenger.sol"; /** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages from L2 onto L1. * In the event that a message sent from L1 to L2 is rejected for exceeding the L2 epoch gas limit, it can be resubmitted * via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver { /*************** * Constructor * ***************/ /** * Pass a default zero address to the address resolver. This will be updated when initialized. */ constructor() Lib_AddressResolver(address(0)) {} /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public { require(address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized."); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; } /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer() { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title iAbs_BaseCrossDomainMessenger */ interface iAbs_BaseCrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); /********************** * Contract Variables * **********************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iAbs_BaseCrossDomainMessenger } from "./iAbs_BaseCrossDomainMessenger.sol"; /** * @title iOVM_L1CrossDomainMessenger */ interface iOVM_L1CrossDomainMessenger is iAbs_BaseCrossDomainMessenger { /******************* * Data Structures * *******************/ struct L2MessageInclusionProof { bytes32 stateRoot; Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader; Lib_OVMCodec.ChainInclusionProof stateRootProof; bytes stateTrieWitness; bytes storageTrieWitness; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _proof Inclusion proof for the given message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; /** * Replays a cross domain message to the target messenger. * @param _target Target contract address. * @param _sender Original sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _gasLimit Gas limit for the provided message. */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol"; /** * @title iOVM_CanonicalTransactionChain */ interface iOVM_CanonicalTransactionChain { /********** * Events * **********/ event TransactionEnqueued( address _l1TxOrigin, address _target, uint256 _gasLimit, bytes _data, uint256 _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); /*********** * Structs * ***********/ struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() external view returns ( iOVM_ChainStorageContainer ); /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() external view returns ( iOVM_ChainStorageContainer ); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() external view returns ( uint40 ); /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement( uint256 _index ) external view returns ( Lib_OVMCodec.QueueElement memory _element ); /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() external view returns ( uint40 ); /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() external view returns ( uint40 ); /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() external view returns ( uint40 ); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() external view returns ( uint40 ); /** * Adds a transaction to the queue. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Appends a given number of queued transactions as a single batch. * @param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 _numQueuedTransactions ) external; /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch( // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) external view returns ( bool ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_ChainStorageContainer */ interface iOVM_ChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata( bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns ( uint256 ); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push( bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push( bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get( uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive( uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) external; /** * Marks an index as overwritable, meaing the underlying buffer can start to write values over * any objects before and including the given index. */ function setNextOverwritableIndex( uint256 _index ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateCommitmentChain */ interface iOVM_StateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch( bytes32[] calldata _batch, uint256 _shouldStartAtElement ) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum EOASignatureType { EIP155_TRANSACTION, ETH_SIGNED_MESSAGE } enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } struct EIP155Transaction { uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint256 chainId; } /********************** * Internal Functions * **********************/ /** * Decodes an EOA transaction (i.e., native Ethereum RLP encoding). * @param _transaction Encoded EOA transaction. * @return Transaction decoded into a struct. */ function decodeEIP155Transaction( bytes memory _transaction, bool _isEthSignedMessage ) internal pure returns ( EIP155Transaction memory ) { if (_isEthSignedMessage) { ( uint256 _nonce, uint256 _gasLimit, uint256 _gasPrice, uint256 _chainId, address _to, bytes memory _data ) = abi.decode( _transaction, (uint256, uint256, uint256, uint256, address ,bytes) ); return EIP155Transaction({ nonce: _nonce, gasPrice: _gasPrice, gasLimit: _gasLimit, to: _to, value: 0, data: _data, chainId: _chainId }); } else { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_transaction); return EIP155Transaction({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), chainId: Lib_RLPReader.readUint256(decoded[6]) }); } } /** * Decompresses a compressed EIP155 transaction. * @param _transaction Compressed EIP155 transaction bytes. * @return Transaction parsed into a struct. */ function decompressEIP155Transaction( bytes memory _transaction ) internal returns ( EIP155Transaction memory ) { return EIP155Transaction({ gasLimit: Lib_BytesUtils.toUint24(_transaction, 0), gasPrice: uint256(Lib_BytesUtils.toUint24(_transaction, 3)) * 1000000, nonce: Lib_BytesUtils.toUint24(_transaction, 6), to: Lib_BytesUtils.toAddress(_transaction, 9), data: Lib_BytesUtils.slice(_transaction, 29), chainId: Lib_SafeExecutionManagerWrapper.safeCHAINID(), value: 0 }); } /** * Encodes an EOA transaction back into the original transaction. * @param _transaction EIP155transaction to encode. * @param _isEthSignedMessage Whether or not this was an eth signed message. * @return Encoded transaction. */ function encodeEIP155Transaction( EIP155Transaction memory _transaction, bool _isEthSignedMessage ) internal pure returns ( bytes memory ) { if (_isEthSignedMessage) { return abi.encode( _transaction.nonce, _transaction.gasLimit, _transaction.gasPrice, _transaction.chainId, _transaction.to, _transaction.data ); } else { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); if (_transaction.to == address(0)) { raw[3] = Lib_RLPWriter.writeBytes(''); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(0); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(bytes('')); raw[8] = Lib_RLPWriter.writeBytes(bytes('')); return Lib_RLPWriter.writeList(raw); } } /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { Ownable } from "./Lib_Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string _name, address _newAddress ); /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ function setAddress( string memory _name, address _address ) public onlyOwner { emit AddressSet(_name, _address); addresses[_getNameHash(_name)] = _address; } function getAddress( string memory _name ) public view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ function _getNameHash( string memory _name ) internal pure returns ( bytes32 _hash ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /******************************************* * Contract Variables: Contract References * *******************************************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ function resolve( string memory _name ) public view returns ( address _contract ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Ownable * @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ abstract contract Ownable { /************* * Variables * *************/ address public owner; /********** * Events * **********/ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /*************** * Constructor * ***************/ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( owner == msg.sender, "Ownable: caller is not the owner" ); _; } /******************** * Public Functions * ********************/ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function transferOwnership(address _newOwner) public virtual onlyOwner { require( _newOwner != address(0), "Ownable: new owner cannot be the zero address" ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return _out The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return _out The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory _out ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return _out The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory _out ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return _out The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return _out The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return _out The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return _encoded RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory _encoded ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return _binary RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory _binary ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return _flattened The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory _flattened ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_MerkleTrie */ library Lib_MerkleTrie { /******************* * Data Structures * *******************/ enum NodeType { BranchNode, ExtensionNode, LeafNode } struct TrieNode { bytes encoded; Lib_RLPReader.RLPItem[] decoded; } /********************** * Contract Constants * **********************/ // TREE_RADIX determines the number of elements per branch node. uint256 constant TREE_RADIX = 16; // Branch nodes have TREE_RADIX elements plus an additional `value` slot. uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1; // Leaf nodes and extension nodes always have two elements, a `path` and a `value`. uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2; // Prefixes are prepended to the `path` within a leaf or extension node and // allow us to differentiate between the two node types. `ODD` or `EVEN` is // determined by the number of nibbles within the unprefixed `path`. If the // number of nibbles if even, we need to insert an extra padding nibble so // the resulting prefixed `path` has an even number of nibbles. uint8 constant PREFIX_EXTENSION_EVEN = 0; uint8 constant PREFIX_EXTENSION_ODD = 1; uint8 constant PREFIX_LEAF_EVEN = 2; uint8 constant PREFIX_LEAF_ODD = 3; // Just a utility constant. RLP represents `NULL` as 0x80. bytes1 constant RLP_NULL = bytes1(0x80); bytes constant RLP_NULL_BYTES = hex'80'; bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES); /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { ( bool exists, bytes memory value ) = get(_key, _proof, _root); return ( exists && Lib_BytesUtils.equal(_value, value) ); } /** * @notice Verifies a proof that a given key is *not* present in * the Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the key is absent in the trie, `false` otherwise. */ function verifyExclusionProof( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { ( bool exists, ) = get(_key, _proof, _root); return exists == false; } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { // Special case when inserting the very first node. if (_root == KECCAK256_RLP_NULL_BYTES) { return getSingleNodeRootHash(_key, _value); } TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root); TrieNode[] memory newPath = _getNewPath(proof, pathLength, keyRemainder, _value); return _getUpdatedTrieRoot(newPath, _key); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root); bool exists = keyRemainder.length == 0; require( exists || isFinalNode, "Provided proof is invalid." ); bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes(''); return ( exists, value ); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { return keccak256(_makeLeafNode( Lib_BytesUtils.toNibbles(_key), _value ).encoded); } /********************* * Private Functions * *********************/ /** * @notice Walks through a proof using a provided key. * @param _proof Inclusion proof to walk through. * @param _key Key to use for the walk. * @param _root Known root of the trie. * @return _pathLength Length of the final path * @return _keyRemainder Portion of the key remaining after the walk. * @return _isFinalNode Whether or not we've hit a dead end. */ function _walkNodePath( TrieNode[] memory _proof, bytes memory _key, bytes32 _root ) private pure returns ( uint256 _pathLength, bytes memory _keyRemainder, bool _isFinalNode ) { uint256 pathLength = 0; bytes memory key = Lib_BytesUtils.toNibbles(_key); bytes32 currentNodeID = _root; uint256 currentKeyIndex = 0; uint256 currentKeyIncrement = 0; TrieNode memory currentNode; // Proof is top-down, so we start at the first element (root). for (uint256 i = 0; i < _proof.length; i++) { currentNode = _proof[i]; currentKeyIndex += currentKeyIncrement; // Keep track of the proof elements we actually need. // It's expensive to resize arrays, so this simply reduces gas costs. pathLength += 1; if (currentKeyIndex == 0) { // First proof element is always the root node. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid root hash" ); } else if (currentNode.encoded.length >= 32) { // Nodes 32 bytes or larger are hashed inside branch nodes. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid large internal hash" ); } else { // Nodes smaller than 31 bytes aren't hashed. require( Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID, "Invalid internal node hash" ); } if (currentNode.decoded.length == BRANCH_NODE_LENGTH) { if (currentKeyIndex == key.length) { // We've hit the end of the key, meaning the value should be within this branch node. break; } else { // We're not at the end of the key yet. // Figure out what the next node ID should be and continue. uint8 branchKey = uint8(key[currentKeyIndex]); Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey]; currentNodeID = _getNodeID(nextNode); currentKeyIncrement = 1; continue; } } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(currentNode); uint8 prefix = uint8(path[0]); uint8 offset = 2 - prefix % 2; bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset); bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex); uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { if ( pathRemainder.length == sharedNibbleLength && keyRemainder.length == sharedNibbleLength ) { // The key within this leaf matches our key exactly. // Increment the key index to reflect that we have no remainder. currentKeyIndex += sharedNibbleLength; } // We've hit a leaf node, so our next node should be NULL. currentNodeID = bytes32(RLP_NULL); break; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { if (sharedNibbleLength == 0) { // Our extension node doesn't share any part of our key. // We've hit the end of this path, updates will need to modify this extension. currentNodeID = bytes32(RLP_NULL); break; } else { // Our extension shares some nibbles. // Carry on to the next node. currentNodeID = _getNodeID(currentNode.decoded[1]); currentKeyIncrement = sharedNibbleLength; continue; } } else { revert("Received a node with an unknown prefix"); } } else { revert("Received an unparseable node."); } } // If our node ID is NULL, then we're at a dead end. bool isFinalNode = currentNodeID == bytes32(RLP_NULL); return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode); } /** * @notice Creates new nodes to support a k/v pair insertion into a given * Merkle trie path. * @param _path Path to the node nearest the k/v pair. * @param _pathLength Length of the path. Necessary because the provided * path may include additional nodes (e.g., it comes directly from a proof) * and we can't resize in-memory arrays without costly duplication. * @param _keyRemainder Portion of the initial key that must be inserted * into the trie. * @param _value Value to insert at the given key. * @return _newPath A new path with the inserted k/v pair and extra supporting nodes. */ function _getNewPath( TrieNode[] memory _path, uint256 _pathLength, bytes memory _keyRemainder, bytes memory _value ) private pure returns ( TrieNode[] memory _newPath ) { bytes memory keyRemainder = _keyRemainder; // Most of our logic depends on the status of the last node in the path. TrieNode memory lastNode = _path[_pathLength - 1]; NodeType lastNodeType = _getNodeType(lastNode); // Create an array for newly created nodes. // We need up to three new nodes, depending on the contents of the last node. // Since array resizing is expensive, we'll keep track of the size manually. // We're using an explicit `totalNewNodes += 1` after insertions for clarity. TrieNode[] memory newNodes = new TrieNode[](3); uint256 totalNewNodes = 0; if (keyRemainder.length == 0 && lastNodeType == NodeType.LeafNode) { // We've found a leaf node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value); totalNewNodes += 1; } else if (lastNodeType == NodeType.BranchNode) { if (keyRemainder.length == 0) { // We've found a branch node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _editBranchValue(lastNode, _value); totalNewNodes += 1; } else { // We've found a branch node, but it doesn't contain our key. // Reinsert the old branch for now. newNodes[totalNewNodes] = lastNode; totalNewNodes += 1; // Create a new leaf node, slicing our remainder since the first byte points // to our branch node. newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value); totalNewNodes += 1; } } else { // Our last node is either an extension node or a leaf node with a different key. bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) { // We've got some shared nibbles between the last node and our key remainder. // We'll need to insert an extension node that covers these shared nibbles. bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength); newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value)); totalNewNodes += 1; // Cut down the keys since we've just covered these shared nibbles. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength); keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength); } // Create an empty branch to fill in. TrieNode memory newBranch = _makeEmptyBranchNode(); if (lastNodeKey.length == 0) { // Key remainder was larger than the key for our last node. // The value within our last node is therefore going to be shifted into // a branch value slot. newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode)); } else { // Last node key was larger than the key remainder. // We're going to modify some index of our branch. uint8 branchKey = uint8(lastNodeKey[0]); // Move on to the next nibble. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1); if (lastNodeType == NodeType.LeafNode) { // We're dealing with a leaf node. // We'll modify the key and insert the old leaf node into the branch index. TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else if (lastNodeKey.length != 0) { // We're dealing with a shrinking extension node. // We need to modify the node to decrease the size of the key. TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else { // We're dealing with an unnecessary extension node. // We're going to delete the node entirely. // Simply insert its current value into the branch index. newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode)); } } if (keyRemainder.length == 0) { // We've got nothing left in the key remainder. // Simply insert the value into the branch value slot. newBranch = _editBranchValue(newBranch, _value); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; } else { // We've got some key remainder to work with. // We'll be inserting a leaf node into the trie. // First, move on to the next nibble. keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; // Push a new leaf node for our k/v pair. newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value); totalNewNodes += 1; } } // Finally, join the old path with our newly created nodes. // Since we're overwriting the last node in the path, we use `_pathLength - 1`. return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes); } /** * @notice Computes the trie root from a given path. * @param _nodes Path to some k/v pair. * @param _key Key for the k/v pair. * @return _updatedRoot Root hash for the updated trie. */ function _getUpdatedTrieRoot( TrieNode[] memory _nodes, bytes memory _key ) private pure returns ( bytes32 _updatedRoot ) { bytes memory key = Lib_BytesUtils.toNibbles(_key); // Some variables to keep track of during iteration. TrieNode memory currentNode; NodeType currentNodeType; bytes memory previousNodeHash; // Run through the path backwards to rebuild our root hash. for (uint256 i = _nodes.length; i > 0; i--) { // Pick out the current node. currentNode = _nodes[i - 1]; currentNodeType = _getNodeType(currentNode); if (currentNodeType == NodeType.LeafNode) { // Leaf nodes are already correctly encoded. // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); } else if (currentNodeType == NodeType.ExtensionNode) { // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. currentNode = _makeExtensionNode(nodeKey, previousNodeHash); } } else if (currentNodeType == NodeType.BranchNode) { // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. uint8 branchKey = uint8(key[key.length - 1]); key = Lib_BytesUtils.slice(key, 0, key.length - 1); currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash); } } // Compute the node hash for the next iteration. previousNodeHash = _getNodeHash(currentNode.encoded); } // Current node should be the root at this point. // Simply return the hash of its encoding. return keccak256(currentNode.encoded); } /** * @notice Parses an RLP-encoded proof into something more useful. * @param _proof RLP-encoded proof to parse. * @return _parsed Proof parsed into easily accessible structs. */ function _parseProof( bytes memory _proof ) private pure returns ( TrieNode[] memory _parsed ) { Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof); TrieNode[] memory proof = new TrieNode[](nodes.length); for (uint256 i = 0; i < nodes.length; i++) { bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]); proof[i] = TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } return proof; } /** * @notice Picks out the ID for a node. Node ID is referred to as the * "hash" within the specification, but nodes < 32 bytes are not actually * hashed. * @param _node Node to pull an ID for. * @return _nodeID ID for the node, depending on the size of its contents. */ function _getNodeID( Lib_RLPReader.RLPItem memory _node ) private pure returns ( bytes32 _nodeID ) { bytes memory nodeID; if (_node.length < 32) { // Nodes smaller than 32 bytes are RLP encoded. nodeID = Lib_RLPReader.readRawBytes(_node); } else { // Nodes 32 bytes or larger are hashed. nodeID = Lib_RLPReader.readBytes(_node); } return Lib_BytesUtils.toBytes32(nodeID); } /** * @notice Gets the path for a leaf or extension node. * @param _node Node to get a path for. * @return _path Node path, converted to an array of nibbles. */ function _getNodePath( TrieNode memory _node ) private pure returns ( bytes memory _path ) { return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0])); } /** * @notice Gets the key for a leaf or extension node. Keys are essentially * just paths without any prefix. * @param _node Node to get a key for. * @return _key Node key, converted to an array of nibbles. */ function _getNodeKey( TrieNode memory _node ) private pure returns ( bytes memory _key ) { return _removeHexPrefix(_getNodePath(_node)); } /** * @notice Gets the path for a node. * @param _node Node to get a value for. * @return _value Node value, as hex bytes. */ function _getNodeValue( TrieNode memory _node ) private pure returns ( bytes memory _value ) { return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]); } /** * @notice Computes the node hash for an encoded node. Nodes < 32 bytes * are not hashed, all others are keccak256 hashed. * @param _encoded Encoded node to hash. * @return _hash Hash of the encoded node. Simply the input if < 32 bytes. */ function _getNodeHash( bytes memory _encoded ) private pure returns ( bytes memory _hash ) { if (_encoded.length < 32) { return _encoded; } else { return abi.encodePacked(keccak256(_encoded)); } } /** * @notice Determines the type for a given node. * @param _node Node to determine a type for. * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode. */ function _getNodeType( TrieNode memory _node ) private pure returns ( NodeType _type ) { if (_node.decoded.length == BRANCH_NODE_LENGTH) { return NodeType.BranchNode; } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(_node); uint8 prefix = uint8(path[0]); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { return NodeType.LeafNode; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { return NodeType.ExtensionNode; } } revert("Invalid node type"); } /** * @notice Utility; determines the number of nibbles shared between two * nibble arrays. * @param _a First nibble array. * @param _b Second nibble array. * @return _shared Number of shared nibbles. */ function _getSharedNibbleLength( bytes memory _a, bytes memory _b ) private pure returns ( uint256 _shared ) { uint256 i = 0; while (_a.length > i && _b.length > i && _a[i] == _b[i]) { i++; } return i; } /** * @notice Utility; converts an RLP-encoded node into our nice struct. * @param _raw RLP-encoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( bytes[] memory _raw ) private pure returns ( TrieNode memory _node ) { bytes memory encoded = Lib_RLPWriter.writeList(_raw); return TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } /** * @notice Utility; converts an RLP-decoded node into our nice struct. * @param _items RLP-decoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](_items.length); for (uint256 i = 0; i < _items.length; i++) { raw[i] = Lib_RLPReader.readRawBytes(_items[i]); } return _makeNode(raw); } /** * @notice Creates a new extension node. * @param _key Key for the extension node, unprefixed. * @param _value Value for the extension node. * @return _node New extension node with the given k/v pair. */ function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * @notice Creates a new leaf node. * @dev This function is essentially identical to `_makeExtensionNode`. * Although we could route both to a single method with a flag, it's * more gas efficient to keep them separate and duplicate the logic. * @param _key Key for the leaf node, unprefixed. * @param _value Value for the leaf node. * @return _node New leaf node with the given k/v pair. */ function _makeLeafNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, true); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * @notice Creates an empty branch node. * @return _node Empty branch node as a TrieNode struct. */ function _makeEmptyBranchNode() private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH); for (uint256 i = 0; i < raw.length; i++) { raw[i] = RLP_NULL_BYTES; } return _makeNode(raw); } /** * @notice Modifies the value slot for a given branch. * @param _branch Branch node to modify. * @param _value Value to insert into the branch. * @return _updatedNode Modified branch node. */ function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = Lib_RLPWriter.writeBytes(_value); _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Modifies a slot at an index for a given branch. * @param _branch Branch node to modify. * @param _index Slot index to modify. * @param _value Value to insert into the slot. * @return _updatedNode Modified branch node. */ function _editBranchIndex( TrieNode memory _branch, uint8 _index, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value); _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Utility; adds a prefix to a key. * @param _key Key to prefix. * @param _isLeaf Whether or not the key belongs to a leaf. * @return _prefixedKey Prefixed key. */ function _addHexPrefix( bytes memory _key, bool _isLeaf ) private pure returns ( bytes memory _prefixedKey ) { uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00); uint8 offset = uint8(_key.length % 2); bytes memory prefixed = new bytes(2 - offset); prefixed[0] = bytes1(prefix + offset); return abi.encodePacked(prefixed, _key); } /** * @notice Utility; removes a prefix from a path. * @param _path Path to remove the prefix from. * @return _unprefixedKey Unprefixed key. */ function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey ) { if (uint8(_path[0]) % 2 == 0) { return Lib_BytesUtils.slice(_path, 2); } else { return Lib_BytesUtils.slice(_path, 1); } } /** * @notice Utility; combines two node arrays. Array lengths are required * because the actual lengths may be longer than the filled lengths. * Array resizing is extremely costly and should be avoided. * @param _a First array to join. * @param _aLength Length of the first array. * @param _b Second array to join. * @param _bLength Length of the second array. * @return _joined Combined node array. */ function _joinNodeArrays( TrieNode[] memory _a, uint256 _aLength, TrieNode[] memory _b, uint256 _bLength ) private pure returns ( TrieNode[] memory _joined ) { TrieNode[] memory ret = new TrieNode[](_aLength + _bLength); // Copy elements from the first array. for (uint256 i = 0; i < _aLength; i++) { ret[i] = _a[i]; } // Copy elements from the second array. for (uint256 i = 0; i < _bLength; i++) { ret[i + _aLength] = _b[i]; } return ret; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol"; /** * @title Lib_SecureMerkleTrie */ library Lib_SecureMerkleTrie { /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root); } /** * @notice Verifies a proof that a given key is *not* present in * the Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the key is not present in the trie, `false` otherwise. */ function verifyExclusionProof( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyExclusionProof(key, _proof, _root); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.update(key, _value, _proof, _root); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.get(key, _proof, _root); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.getSingleNodeRootHash(key, _value); } /********************* * Private Functions * *********************/ /** * Computes the secure counterpart to a key. * @param _key Key to get a secure key from. * @return _secureKey Secure version of the key. */ function _getSecureKey( bytes memory _key ) private pure returns ( bytes memory _secureKey ) { return abi.encodePacked(keccak256(_key)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice( bytes memory _bytes, uint256 _start ) internal pure returns (bytes memory) { if (_bytes.length - _start == 0) { return bytes(''); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns (bytes32) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3 , "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract Lib_ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; /** * @title Lib_SafeExecutionManagerWrapper * @dev The Safe Execution Manager Wrapper provides functions which facilitate writing OVM safe * code using the standard solidity compiler, by routing all its operations through the Execution * Manager. * * Compiler used: solc * Runtime target: OVM */ library Lib_SafeExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeCALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmDELEGATECALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeDELEGATECALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmDELEGATECALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmCREATE call. * @param _gasLimit Gas limit for the creation. * @param _bytecode Code for the new contract. * @return _contract Address of the created contract. */ function safeCREATE( uint256 _gasLimit, bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _safeExecutionManagerInteraction( _gasLimit, abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmEXTCODESIZE call. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function safeEXTCODESIZE( address _contract ) internal returns ( uint256 _EXTCODESIZE ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmEXTCODESIZE(address)", _contract ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCHAINID call. * @return _CHAINID Result of calling ovmCHAINID. */ function safeCHAINID() internal returns ( uint256 _CHAINID ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCALLER call. * @return _CALLER Result of calling ovmCALLER. */ function safeCALLER() internal returns ( address _CALLER ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALLER()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmADDRESS call. * @return _ADDRESS Result of calling ovmADDRESS. */ function safeADDRESS() internal returns ( address _ADDRESS ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmGETNONCE call. * @return _nonce Result of calling ovmGETNONCE. */ function safeGETNONCE() internal returns ( uint256 _nonce ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function safeINCREMENTNONCE() internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function safeCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Performs a safe REVERT. * @param _reason String revert reason to pass along with the REVERT. */ function safeREVERT( string memory _reason ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmREVERT(bytes)", Lib_ErrorUtils.encodeRevertString( _reason ) ) ); } /** * Performs a safe "require". * @param _condition Boolean condition that must be true or will revert. * @param _reason String revert reason to pass along with the REVERT. */ function safeREQUIRE( bool _condition, string memory _reason ) internal { if (!_condition) { safeREVERT( _reason ); } } /** * Performs a safe ovmSLOAD call. */ function safeSLOAD( bytes32 _key ) internal returns ( bytes32 ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSLOAD(bytes32)", _key ) ); return abi.decode(returndata, (bytes32)); } /** * Performs a safe ovmSSTORE call. */ function safeSSTORE( bytes32 _key, bytes32 _value ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSSTORE(bytes32,bytes32)", _key, _value ) ); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _gasLimit Gas limit for the interaction. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return _returndata Data sent back by the OVM_ExecutionManager. */ function _safeExecutionManagerInteraction( uint256 _gasLimit, bytes memory _calldata ) private returns ( bytes memory _returndata ) { address ovmExecutionManager = msg.sender; ( bool success, bytes memory returndata ) = ovmExecutionManager.call{gas: _gasLimit}(_calldata); if (success == false) { assembly { revert(add(returndata, 0x20), mload(returndata)) } } else if (returndata.length == 1) { assembly { return(0, 1) } } else { return returndata; } } function _safeExecutionManagerInteraction( bytes memory _calldata ) private returns ( bytes memory _returndata ) { return _safeExecutionManagerInteraction( gasleft(), _calldata ); } }
iOVM_CanonicalTransactionChain/
interface iOVM_CanonicalTransactionChain { event TransactionEnqueued( address _l1TxOrigin, address _target, uint256 _gasLimit, bytes _data, uint256 _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol"; function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) external; } pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } }
10,480,416
./full_match/4/0xae06b02bDf0cF9DC45E810Ec589bD00212423e23/sources/contracts/MeFi.sol
Allows requesters to cancel requests sent to this oracle contract. Will transfer the LINK sent for the request back to the requester's address. Given params must hash to a commitment stored on the contract in order for the request to be valid Emits CancelOracleRequest event. _requestId The request ID _payment The amount of payment given (specified in wei) _callbackFunc The requester's specified callback address _expiration The time of the expiration for the request/ solhint-disable-next-line not-rely-on-time
function cancelOracleRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) external override { bytes32 paramsHash = keccak256( abi.encodePacked( _payment, msg.sender, _callbackFunc, _expiration) ); require(paramsHash == commitments[_requestId], "Params do not match request ID"); require(_expiration <= now, "Request is not expired"); delete commitments[_requestId]; emit CancelOracleRequest(_requestId); assert(MDT.transfer(msg.sender, _payment)); }
808,504
// File: contracts/compound/ComptrollerInterface.sol pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); function getLiquidationIncentive(address cTokenCollateral) public view returns (uint); } // File: contracts/compound/InterestRateModel.sol pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // File: contracts/compound/CTokenInterfaces.sol pragma solidity ^0.5.16; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } // File: contracts/compound/ErrorReporter.sol pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // File: contracts/compound/CarefulMath.sol pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File: contracts/compound/Exponential.sol pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/compound/EIP20Interface.sol pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // File: contracts/compound/EIP20NonStandardInterface.sol pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // File: contracts/compound/CToken.sol pragma solidity ^0.5.16; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint); /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // File: contracts/compound/PriceOracle.sol pragma solidity ^0.5.16; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } // File: contracts/compound/ComptrollerStorage.sol pragma solidity ^0.5.16; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; /** * @notice Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint borrowFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint liquidationIncentiveMantissa; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } // File: contracts/compound/Unitroller.sol pragma solidity ^0.5.16; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } // File: contracts/compound/Comptroller.sol pragma solidity ^0.5.16; /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice Emitted when borrow factor for a cToken is changed event NewBorrowFactor(CToken indexed cToken, uint newBorrowFactor); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) public returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) public returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) public returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; Exp borrowFactorMantissa; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint); /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; uint liquidationIncentive = getLiquidationIncentive(cTokenCollateral); (mathErr, numerator) = mulExp(liquidationIncentive, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } function getLiquidationIncentive(address cToken) public view returns (uint) { uint cTokenLiquidationIncentive = markets[cToken].liquidationIncentiveMantissa; if (cTokenLiquidationIncentive == 0) return liquidationIncentiveMantissa; return cTokenLiquidationIncentive; } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) external returns (uint); /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } function _setLiquidationIncentive(CToken cToken, uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive market.liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint); function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given borrow factors for the given cToken markets. * @dev Admin function to set the borrow factors. * @param cToken The addresses of the markets (tokens) to change the borrow factors for * @param newBorrowFactor The new borrow factor values in underlying to be set. Must be between (0, 1] */ function _setBorrowFactor(CToken cToken, uint newBorrowFactor) external { require(msg.sender == admin, "!admin"); require(newBorrowFactor > 0 && newBorrowFactor <= borrowFactorMaxMantissa, "!borrowFactor"); markets[address(cToken)].borrowFactorMantissa = newBorrowFactor; emit NewBorrowFactor(cToken, newBorrowFactor); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) external returns (bool) { require(markets[address(cToken)].isListed, "!listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "!admin"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) external returns (bool) { require(markets[address(cToken)].isListed, "!listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "!admin"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "!admin"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) external returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "!admin"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "!admin"); require(unitroller._acceptImplementation() == 0, "!authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory utility = mul_(assetPrice, cToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint); /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "!listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "only admin can change comp rate"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeedsInternal(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "!listed"); require(market.isComped == false, "already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0xc00e94Cb662C3520282E6f5717214004A7f26888; } } // File: contracts/Ownable.sol pragma solidity ^0.5.16; contract Ownable { address public _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/QsConfig.sol pragma solidity ^0.5.16; contract QsConfig is Ownable, Exponential { bool public compSpeedGuardianPaused = true; address public compToken; uint public safetyVaultRatio; address public safetyVault; address public safetyGuardian; address public pendingSafetyGuardian; struct MarketCap { /** * The borrow capacity of the asset, will be checked in borrowAllowed() * 0 means there is no limit on the capacity */ uint borrowCap; /** * The supply capacity of the asset, will be checked in mintAllowed() * 0 means there is no limit on the capacity */ uint supplyCap; /** * The flash loan capacity of the asset, will be checked in flashLoanAllowed() * 0 means there is no limit on the capacity */ uint flashLoanCap; } uint public compRatio = 0.5e18; mapping(address => bool) public whitelist; mapping(address => bool) public blacklist; mapping(address => MarketCap) marketsCap; // creditLimits allowed specific protocols to borrow and repay without collateral mapping(address => uint) public creditLimits; uint public flashLoanFeeRatio = 0.0001e18; event NewCompToken(address oldCompToken, address newCompToken); event NewSafetyVault(address oldSafetyVault, address newSafetyVault); event NewSafetyVaultRatio(uint oldSafetyVaultRatio, uint newSafetyVault); event NewCompRatio(uint oldCompRatio, uint newCompRatio); event WhitelistChange(address user, bool enabled); event BlacklistChange(address user, bool enabled); /// @notice Emitted when protocol's credit limit has changed event CreditLimitChanged(address protocol, uint creditLimit); event FlashLoanFeeRatioChanged(uint oldFeeRatio, uint newFeeRatio); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(address indexed cToken, uint newBorrowCap); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(address indexed cToken, uint newSupplyCap); /// @notice Emitted when flash loan for a cToken is changed event NewFlashLoanCap(address indexed cToken, uint newFlashLoanCap); constructor(QsConfig previousQsConfig) public { if (address(previousQsConfig) == address(0x0)) return; compToken = previousQsConfig.compToken(); safetyVaultRatio = previousQsConfig.safetyVaultRatio(); safetyVault = previousQsConfig.safetyVault(); safetyGuardian = msg.sender; } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(address[] calldata cTokens, uint[] calldata newBorrowCaps) external onlyOwner { uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { marketsCap[cTokens[i]].borrowCap = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Set the given flash loan caps for the given cToken markets. Borrowing that brings total flash cap to or above flash loan cap will revert. * @dev Admin function to set the flash loan caps. A flash loan cap of 0 corresponds to unlimited flash loan. * @param cTokens The addresses of the markets (tokens) to change the flash loan caps for * @param newFlashLoanCaps The new flash loan cap values in underlying to be set. A value of 0 corresponds to unlimited flash loan. */ function _setMarketFlashLoanCaps(address[] calldata cTokens, uint[] calldata newFlashLoanCaps) external onlyOwner { uint numMarkets = cTokens.length; uint numFlashLoanCaps = newFlashLoanCaps.length; require(numMarkets != 0 && numMarkets == numFlashLoanCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { marketsCap[cTokens[i]].flashLoanCap = newFlashLoanCaps[i]; emit NewFlashLoanCap(cTokens[i], newFlashLoanCaps[i]); } } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supply to or above supply cap will revert. * @dev Admin function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(address[] calldata cTokens, uint[] calldata newSupplyCaps) external onlyOwner { uint numMarkets = cTokens.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { marketsCap[cTokens[i]].supplyCap = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Sets whitelisted protocol's credit limit * @param protocol The address of the protocol * @param creditLimit The credit limit */ function _setCreditLimit(address protocol, uint creditLimit) public { require(msg.sender == owner(), "only owner can set protocol credit limit"); creditLimits[protocol] = creditLimit; emit CreditLimitChanged(protocol, creditLimit); } function _setCompToken(address _compToken) public onlyOwner { address oldCompToken = compToken; compToken = _compToken; emit NewCompToken(oldCompToken, compToken); } function _setSafetyVault(address _safetyVault) public onlyOwner { address oldSafetyVault = safetyVault; safetyVault = _safetyVault; emit NewSafetyVault(oldSafetyVault, safetyVault); } function _setSafetyVaultRatio(uint _safetyVaultRatio) public onlyOwner { uint oldSafetyVaultRatio = safetyVaultRatio; safetyVaultRatio = _safetyVaultRatio; emit NewSafetyVaultRatio(oldSafetyVaultRatio, safetyVaultRatio); } function _setCompSpeedGuardianPaused(bool state) public onlyOwner returns (bool) { compSpeedGuardianPaused = state; return state; } function _setPendingSafetyGuardian(address newPendingSafetyGuardian) external { require(msg.sender == safetyGuardian, "!safetyGuardian"); pendingSafetyGuardian = newPendingSafetyGuardian; } function _acceptSafetyGuardian() external { require(msg.sender == pendingSafetyGuardian, "!pendingSafetyGuardian"); safetyGuardian = pendingSafetyGuardian; pendingSafetyGuardian = address(0x0); } function getCreditLimit(address protocol) external view returns (uint) { return creditLimits[protocol]; } function getBorrowCap(address cToken) external view returns (uint) { return marketsCap[cToken].borrowCap; } function getSupplyCap(address cToken) external view returns (uint) { return marketsCap[cToken].supplyCap; } function getFlashLoanCap(address cToken) external view returns (uint) { return marketsCap[cToken].flashLoanCap; } function calculateSeizeTokenAllocation(uint _seizeTokenAmount, uint liquidationIncentiveMantissa) public view returns(uint liquidatorAmount, uint safetyVaultAmount) { Exp memory vaultRatio = Exp({mantissa:safetyVaultRatio}); (,Exp memory tmp) = mulScalar(vaultRatio, _seizeTokenAmount); safetyVaultAmount = div_(tmp, liquidationIncentiveMantissa).mantissa; liquidatorAmount = sub_(_seizeTokenAmount, safetyVaultAmount); } function getCompAllocation(address user, uint userAccrued) public view returns(uint userAmount, uint governanceAmount) { if (!isContract(user) || whitelist[user]) { return (userAccrued, 0); } Exp memory compRatioExp = Exp({mantissa:compRatio}); (, userAmount) = mulScalarTruncate(compRatioExp, userAccrued); governanceAmount = sub_(userAccrued, userAmount); } function getFlashFee(address borrower, address token, uint256 amount) external view returns (uint flashFee) { if (whitelist[borrower]) { return 0; } Exp memory flashLoanFeeRatioExp = Exp({mantissa:flashLoanFeeRatio}); (, flashFee) = mulScalarTruncate(flashLoanFeeRatioExp, amount); token; } function _setCompRatio(uint _compRatio) public onlyOwner { require(_compRatio < 1e18, "compRatio should be less then 100%"); uint oldCompRatio = compRatio; compRatio = _compRatio; emit NewCompRatio(oldCompRatio, compRatio); } function isBlocked(address user) public view returns (bool) { return blacklist[user]; } function _addToWhitelist(address _member) public onlyOwner { require(_member != address(0x0), "Zero address is not allowed"); whitelist[_member] = true; emit WhitelistChange(_member, true); } function _removeFromWhitelist(address _member) public onlyOwner { require(_member != address(0x0), "Zero address is not allowed"); whitelist[_member] = false; emit WhitelistChange(_member, false); } function _addToBlacklist(address _member) public onlyOwner { require(_member != address(0x0), "Zero address is not allowed"); blacklist[_member] = true; emit BlacklistChange(_member, true); } function _removeFromBlacklist(address _member) public onlyOwner { require(_member != address(0x0), "Zero address is not allowed"); blacklist[_member] = false; emit BlacklistChange(_member, false); } function _setFlashLoanFeeRatio(uint _feeRatio) public onlyOwner { require(_feeRatio != flashLoanFeeRatio, "Same fee ratio already set"); require(_feeRatio < 1e18, "Invalid fee ratio"); uint oldFeeRatio = flashLoanFeeRatio; flashLoanFeeRatio = _feeRatio; emit FlashLoanFeeRatioChanged(oldFeeRatio, flashLoanFeeRatio); } function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/Qstroller.sol pragma solidity ^0.5.16; contract Qstroller is Comptroller { /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); QsConfig public qsConfig; // /** // * @notice Remove the market from the markets mapping // * @param cToken The address of the market (token) to delist // */ // function _delistMarket(CToken cToken) external { // require(msg.sender == admin, "only admin may delist market"); // // require(markets[address(cToken)].isListed, "market not listed"); // require(cToken.totalSupply() == 0, "market not empty"); // // cToken.isCToken(); // Sanity check to make sure its really a CToken // // delete markets[address(cToken)]; // // for (uint i = 0; i < allMarkets.length; i++) { // if (allMarkets[i] == cToken) { // allMarkets[i] = allMarkets[allMarkets.length - 1]; // delete allMarkets[allMarkets.length - 1]; // allMarkets.length--; // break; // } // } // // emit MarketDelisted(cToken); // } function _setQsConfig(QsConfig _qsConfig) public { require(msg.sender == admin); qsConfig = _qsConfig; } /** * @notice Sets new governance token distribution speed * @dev Admin function to set new token distribution speed */ function _setCompSpeeds(address[] memory _allMarkets, uint[] memory _compSpeeds) public { // Check caller is admin require(msg.sender == admin); require(_allMarkets.length == _compSpeeds.length); uint _compRate = 0; for (uint i = 0; i < _allMarkets.length; i++) { address cToken = _allMarkets[i]; Market storage market = markets[cToken]; if (market.isComped == false) { _addCompMarketInternal(cToken); } compSpeeds[cToken] = _compSpeeds[i]; _compRate = add_(_compRate, _compSpeeds[i]); } _setCompRate(_compRate); } function refreshCompSpeeds() public { require(!qsConfig.compSpeedGuardianPaused()); require(msg.sender == tx.origin); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { if (qsConfig.compSpeedGuardianPaused()) { return; } else { super.refreshCompSpeedsInternal(); } } function getCompAddress() public view returns (address) { return qsConfig.compToken(); } function calculateSeizeTokenAllocation(uint _seizeTokenAmount) public view returns(uint liquidatorAmount, uint safetyVaultAmount) { return qsConfig.calculateSeizeTokenAllocation(_seizeTokenAmount, liquidationIncentiveMantissa); } function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { address compAddress = getCompAddress(); if (userAccrued >= threshold && userAccrued > 0 && compAddress != address(0x0)) { EIP20Interface comp = EIP20Interface(compAddress); uint compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { (uint userAmount, uint governanceAmount) = qsConfig.getCompAllocation(user, userAccrued); if (userAmount > 0) comp.transfer(user, userAmount); if (governanceAmount > 0) comp.transfer(qsConfig.safetyVault(), governanceAmount); return 0; } } return userAccrued; } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "!cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = qsConfig.getBorrowCap(cToken); // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); (MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount); require(mathErr == MathError.NO_ERROR, "overflow"); require(nextTotalBorrows < borrowCap, "cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function flashLoanAllowed(address cToken, address to, uint256 flashLoanAmount) view external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } uint flashLoanCap = qsConfig.getFlashLoanCap(cToken); // FlashLoan cap of 0 corresponds to unlimited flash loan if (flashLoanCap != 0) { require(flashLoanAmount <= flashLoanCap, "cap reached"); } to; return uint(Error.NO_ERROR); } function getFlashLoanCap(address cToken) view external returns (uint) { return qsConfig.getFlashLoanCap(cToken); } /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { require(!qsConfig.isBlocked(minter)); // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken]); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } uint supplyCap = qsConfig.getSupplyCap(cToken); // Supply cap of 0 corresponds to unlimited borrowing if (supplyCap != 0) { Exp memory exchangeRate = Exp({mantissa: CTokenInterface(cToken).exchangeRateCurrent()}); (MathError mErr, uint totalSupplyUnderlying) = mulScalarTruncate(exchangeRate, EIP20Interface(cToken).totalSupply()); require(mErr == MathError.NO_ERROR); (MathError mathErr, uint nextTotalSupplyUnderlying) = addUInt(totalSupplyUnderlying, mintAmount); require(mathErr == MathError.NO_ERROR); require(nextTotalSupplyUnderlying <= supplyCap, "cap reached"); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } <<<<<<< HEAD ======= /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; // use first 128 bit as supplySpeed supplySpeed = supplySpeed >> 128 == 0 ? supplySpeed : supplySpeed >> 128; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index: safe224(index.mantissa, " 224bits"), block: safe32(blockNumber, "> 32bits") }); } else if (deltaBlocks > 0 && supplyState.index > 0) { supplyState.block = safe32(blockNumber, "> 32bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; // use last 128 bit as borrowSpeed uint borrowSpeed = uint128(compSpeeds[cToken]); uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "> 224bits"), block: safe32(blockNumber, "> 32bits") }); } else if (deltaBlocks > 0 && borrowState.index > 0) { borrowState.block = safe32(blockNumber, "> 32bits"); } } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { // If credit limit is set to MAX, no need to check account liquidity. if (qsConfig.getCreditLimit(account) == uint(-1)) { return (Error.NO_ERROR, uint(-1), 0); } AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.borrowFactorMantissa = Exp({mantissa: markets[address(asset)].borrowFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrowValue = borrowBalance / borrowFactor uint borrowValue = div_(vars.borrowBalance, vars.borrowFactorMantissa); // sumBorrowPlusEffects += oraclePrice * borrowValue (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowValue, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // borrowValue = borrowAmount / borrowFactor borrowValue = div_(borrowAmount, vars.borrowFactorMantissa); // sumBorrowPlusEffects += oraclePrice * borrowValue (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowValue, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // If credit limit is set, no need to consider collateral. if (qsConfig.getCreditLimit(account) > 0) { vars.sumCollateral = qsConfig.getCreditLimit(account); } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) public returns (uint) { require(qsConfig.getCreditLimit(borrower) == 0 , "credit account"); return super.liquidateBorrowAllowed(cTokenBorrowed, cTokenCollateral, liquidator, borrower, repayAmount); } function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) public returns (uint) { require(qsConfig.getCreditLimit(borrower) == 0 , "credit account"); return super.seizeAllowed(cTokenCollateral, cTokenBorrowed, liquidator, borrower, seizeTokens); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) public returns (uint) { require(qsConfig.getCreditLimit(borrower) == 0 || payer == borrower, "Payer != borrower"); return super.repayBorrowAllowed(cToken, payer, borrower, repayAmount); } function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != qsConfig.safetyGuardian()) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0, borrowFactorMantissa: 1e18, liquidationIncentiveMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) external returns (uint) { // Check caller is admin if (msg.sender != qsConfig.safetyGuardian()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } >>>>>>> f75be7e... update flat files }
Remove a market from compMarkets, preventing it from earning COMP in the flywheel cToken The address of the market to drop/
function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); }
6,421,989
// pragma solidity ^0.4.25; pragma solidity ^0.8.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./FlightSuretyData.sol"; // this is not required since interface is defined at the end of this file for reference. /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // operational flag bool private operational = true; // registration fee uint256 public constant registrationFee = 10 ether; uint16 public constant PAYOUT_PERCENT = 150; // Flight status codes. For status codes 20, 40, 50 airline pays out to the insured customer. uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract // reference to Data Contract FlightSuretyData private flightSuretyData; /**** moved to Data Contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; ***************/ /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireRegisteredAirline() { require(flightSuretyData.isAirlineRegistered(msg.sender),"Invalid caller - not registered"); _; } /***** modifier requireRegisteredAndPaidAirline() { require(flightSuretyData.isAirlineRegisteredAndPaid(msg.sender),"Invalid caller - not registerede and paid"); _; } *******/ modifier requireFlightNotRegistered(string memory flightId, address airline, uint256 timestamp) { string memory rflightId; uint256 flightTime; address airlineAddress; bool isRegistered; uint8 statusCode; bytes32 flightKey = getFlightKey(airline, flightId, timestamp); (rflightId, airlineAddress, flightTime, isRegistered, statusCode) = flightSuretyData.getFlight(flightKey); require(!isRegistered, "Flight already registered"); _; } modifier requireFlightRegistered(string memory flightId, address airline, uint256 timestamp) { string memory rflightId; uint256 flightTime; address airlineAddress; bool isRegistered; uint8 statusCode; bytes32 flightKey = getFlightKey(airline, flightId, timestamp); (rflightId, airlineAddress, flightTime, isRegistered, statusCode) = flightSuretyData.getFlight(flightKey); require(isRegistered, "Flight not registered for insurance purchase"); _; } modifier requireNotPaid() { address airlineAddress; string memory airlineName; bool regPaid; bool isReg; uint256 paidAmt; (airlineAddress, airlineName, regPaid, paidAmt, isReg) = flightSuretyData.getAirline(msg.sender); require(regPaid == false, "Registration has been paid"); _; } modifier requireRegAmount() { require(msg.value >= 1, "Minimum of 1 ether required for registration amount"); _; } modifier requireCustomerNotPaid(string memory flightId, address airline, uint256 flightTime) { bytes32 flightKey = getFlightKey(airline, flightId, flightTime); require(!flightSuretyData.hasCustomerPaid(msg.sender, flightKey)); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address _flightSuretyData, address firstAirline) { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(payable(_flightSuretyData)); // flightSuretyData.authorizeContract(address(this)); // flightSuretyData.authorizeContract(firstAirline); // done from deployment script // flightSuretyData.registerAirline(firstAirline); // done from deployment script } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return operational; // Modify to call data contract's status } function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ // Airline making payment for registration. This method accepts payment from airlines for // registration. This is a prerequisite for registration. Until airlines have paid, other // airline cannot propose to register an airline. function makeRegPayment(string memory airlineName) requireIsOperational requireNotPaid requireRegAmount external payable { uint256 paidAmount = msg.value; // registration amount required is 1 ether. Return excess value uint256 surplus = paidAmount - registrationFee; // change state (effects) bool regPaid = true; flightSuretyData.acceptPayment{value: msg.value}(msg.sender, registrationFee, airlineName,regPaid); // do interaction payable(msg.sender).transfer(surplus); } /** * @dev Add an airline to the registration queue * */ function registerAirline(address airline) requireIsOperational requireRegisteredAirline external // returns(bool success, uint256 votes) { if (!flightSuretyData.isAirlineRegistered(airline)) { // check the number of alirline registered if (flightSuretyData.getRegisteredAirlines().length < 4) { // register the airline flightSuretyData.registerAirline(airline); } else { // reg airline count is >=4, put it in reg queue // if 50% of vote is there, then register the airline if (!flightSuretyData.hasSenderVoted(msg.sender, airline)) { // add the votef flightSuretyData.addVote(msg.sender, airline); // get the number of votes. if > 50% of reg airlines, register the airline uint voteCount = flightSuretyData.getVotes(airline).length; uint regAirlineCount = flightSuretyData.getRegisteredAirlines().length; // if (voteCount >= regAirlineCount/2) { if ((voteCount*100)/regAirlineCount >= 50) { // register the airline. All conditions are satisfied flightSuretyData.registerAirline(airline); // TODO: clean (delete) the reg queue for the airline } } } } // return (success, 0); } function isAirlineRegistered(address airline) requireRegisteredAirline view external returns(bool) { return flightSuretyData.isAirlineRegistered(airline); } function getRegisteredAirlines() requireRegisteredAirline view external returns(address[] memory) { return flightSuretyData.getRegisteredAirlines(); } /** * @dev Register a future flight for insuring. * */ function registerFlight (string memory flightId, uint256 flightTime) requireIsOperational requireRegisteredAirline requireFlightNotRegistered(flightId, msg.sender, flightTime) external { address airlineAddress = msg.sender; flightSuretyData.registerFlight(airlineAddress, flightId, flightTime); } // purchase insurance for a flight. Customers call this method to purchase flight insurance function purchaseFlightInsurance(string memory flightId, address airline, uint256 flightTime) requireIsOperational // requireCustomerNotPaid(flightId, airline, flightTime) requireFlightRegistered(flightId, airline, flightTime) external payable { bytes32 flightKey = getFlightKey(airline, flightId, flightTime); flightSuretyData.buy{value: msg.value}(flightKey, msg.sender, msg.value); // flightSuretyData.buy{value: msg.value}(getFlightKey(airline, flightId, flightTime), msg.sender, msg.value); } /** * @dev Called after oracle has updated flight status. TODO: Determine the payouts if the flight was delayed * */ function processFlightStatus ( bytes32 requestKey, uint8 statusCode ) internal { uint256 premiumAmt; uint256 payoutAmt; // check if status code is 20, 40 or 50. // For these status codes, payout needds to happen to the customer. // payout is 1.5 times. // fetch the customers who has insured for the flight. // multiply the paid amout by 1.5 and transfer ether from data contract to customer if (statusCode == 20 || statusCode == 40 || statusCode == 50) { // get insured customer list address[] memory insuredCustomers = flightSuretyData.getInsuredCustomers(requestKey); // get the customer premium for each insured customer and make payment for (uint8 i; i< insuredCustomers.length; i++) { premiumAmt = flightSuretyData.getCustomerPremium(insuredCustomers[i], requestKey); payoutAmt = (premiumAmt * PAYOUT_PERCENT)/100; flightSuretyData.makePayout(insuredCustomers[i],payoutAmt); } } } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string memory flight, uint256 timestamp ) external returns(bytes32) { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // my addtion to fix the compile problem /**** Gopi commented outto replance it idfferently for solidity v > 0.7.0 oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true, responses: newResponses }); */ // for solidity v0.7.0 and greater // initialize ResponseInfof for the request flightSuretyData.initializeRespInfo(key, msg.sender, index); /****** moved to Data str ResponseInfo storage newResponseInfo = oracleResponses[key]; newResponseInfo.requester = msg.sender; newResponseInfo.isOpen = true; ****** */ emit OracleRequest(index, airline, flight, timestamp); return key; } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; /**** data structures moved from here to Data Contract */ // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); event InsuredCustomers(address[] insuredCustomers); event RespEventCode(uint8 statusCode); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); modifier requireRegFee() { string memory messag = "Caller did not send registration fee of "; string memory regFee = string(abi.encodePacked(bytes32(REGISTRATION_FEE))); require(msg.value >= REGISTRATION_FEE, string(abi.encodePacked(messag, regFee))); _; } // Register an oracle with the contract. function registerOracle ( ) external payable requireRegFee { // Require registration fee. Below line commented out. Functionality moved to modifier // require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[] memory indexes = generateIndexes(msg.sender); flightSuretyData.registerOracle{value: msg.value}(msg.sender, indexes); /**** moved to Data Contract oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); **** moved to data contract *****/ } // Obtain indexes for the given oracle function getOracle ( address account ) public view returns(uint8[] memory) { require(flightSuretyData.isOracleRegistered(account), "Oracle not registered"); return flightSuretyData.getOracleIndexes(account); } function getMyIndexes ( ) view public returns(uint8[] memory) { // require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); require(flightSuretyData.isOracleRegistered(msg.sender), "Oracle not registered"); // return oracles[msg.sender].indexes; // moved to Data contract return flightSuretyData.getOracleIndexes(msg.sender); } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external { uint8[] memory orclIndexes = getOracle(msg.sender); require((orclIndexes[0] == index) || (orclIndexes[1] == index) || (orclIndexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // ensure the index receives is the same as the index associated with the flight status request uint8 reqIndex = flightSuretyData.getRequestIndex(key); // require(oracleResponses[key].index == index, "index received is not the index in flight status request"); require(reqIndex == index, "index received is not the index in flight status request"); bool reqOpen = flightSuretyData.isRequestOpen(key); // should be either open or close . If close do nothing require(reqOpen,"No longer open for response"); // add the oracle's response flightSuretyData.addOrclResponse(key, msg.sender, statusCode); // oracleResponses[key].responses[statusCode].push(msg.sender); // moved to Data Contract // emit an event for each valid response received. emit OracleReport(airline, flight, timestamp, statusCode); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information address[] memory orclResponses = flightSuretyData.getOrclResponses(key, statusCode); if (orclResponses.length >= MIN_RESPONSES) { // close the request flightSuretyData.closeOrclResponse(key); // close the request. No further responses will be accepted. // Handle flight status as appropriate.. // processFlightStatus(key, statusCode); // BUG was here. See the description belowmoved to Data contract processFlightStatus(getFlightKey(airline, flight, timestamp), statusCode); // flightSuretyData.creditInsurees(key, statusCode); // THIS WAS THE BUG. WAS HARD TO FIND WITHOUT THE console output in truffle. Used hardhat to identify it. // flightSuretyData.creditInsurees(getFlightKey(airline, flight, timestamp), statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure public returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[] memory) { uint8[] memory indexes = new uint8[](3); indexes[0] = getRandomIndex(account); /* indexes.push(getRandomIndex(account)); indexes.push(getRandomIndex(account)); indexes.push(getRandomIndex(account)); */ indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } if (random == 0) { random = 4;} return random; } // endregion } /* // add reference to FlightData Contract. Similar to itnerface interface FlightSuretyData { // add all the public functions here function registerAirline(address airline) external; function buy() external payable; function creditInsurees() external; function pay() external; function fund() external payable; function getFlightKey(address airline, string memory flight, uint256 timestamp) external returns(bytes32); } */ /***** Before refactoring function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); // ensure the index receives is the same as the index associated with the flight status request require(oracleResponses[key].index == index, "index received is not the index in flight status request"); require(oracleResponses[key].isOpen,"No longer open for response"); oracleResponses[key].responses[statusCode].push(msg.sender); // emit an event for each valid response received. emit OracleReport(airline, flight, timestamp, statusCode); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); oracleResponses[key].isOpen = false; // close the request. No further responses will be accepted. // Handle flight status as appropriate.. TODO processFlightStatus(airline, flight, timestamp, statusCode); } } *************** */
Handle flight status as appropriate.. TODO
function submitOracleResponse ( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) external if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); processFlightStatus(airline, flight, timestamp, statusCode); }
989,314
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "../core/State.sol"; import "../events/ProtocolSettingsEvents.sol"; import "../openzeppelin/SafeERC20.sol"; import "../mixins/ProtocolTokenUser.sol"; contract ProtocolSettings is State, ProtocolTokenUser, ProtocolSettingsEvents { using SafeERC20 for IERC20; constructor() public {} function() external { revert("fallback not allowed"); } function initialize(address target) external onlyOwner { _setTarget(this.setPriceFeedContract.selector, target); _setTarget(this.setSwapsImplContract.selector, target); _setTarget(this.setLoanPool.selector, target); _setTarget(this.setSupportedTokens.selector, target); _setTarget(this.setLendingFeePercent.selector, target); _setTarget(this.setTradingFeePercent.selector, target); _setTarget(this.setBorrowingFeePercent.selector, target); _setTarget(this.setAffiliateFeePercent.selector, target); _setTarget(this.setLiquidationIncentivePercent.selector, target); _setTarget(this.setMaxDisagreement.selector, target); _setTarget(this.setSourceBuffer.selector, target); _setTarget(this.setMaxSwapSize.selector, target); _setTarget(this.setFeesController.selector, target); _setTarget(this.withdrawLendingFees.selector, target); _setTarget(this.withdrawTradingFees.selector, target); _setTarget(this.withdrawBorrowingFees.selector, target); _setTarget(this.withdrawProtocolToken.selector, target); _setTarget(this.depositProtocolToken.selector, target); _setTarget(this.getLoanPoolsList.selector, target); _setTarget(this.isLoanPool.selector, target); _setTarget(this.setSovrynSwapContractRegistryAddress.selector, target); _setTarget(this.setWrbtcToken.selector, target); _setTarget(this.setProtocolTokenAddress.selector, target); _setTarget(this.setRolloverBaseReward.selector, target); _setTarget(this.setRebatePercent.selector, target); } function setPriceFeedContract(address newContract) external onlyOwner { address oldContract = priceFeeds; priceFeeds = newContract; emit SetPriceFeedContract(msg.sender, oldContract, newContract); } function setSwapsImplContract(address newContract) external onlyOwner { address oldContract = swapsImpl; swapsImpl = newContract; emit SetSwapsImplContract(msg.sender, oldContract, newContract); } function setLoanPool(address[] calldata pools, address[] calldata assets) external onlyOwner { require(pools.length == assets.length, "count mismatch"); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != assets[i], "pool == asset"); require(pools[i] != address(0), "pool == 0"); require( assets[i] != address(0) || loanPoolToUnderlying[pools[i]] != address(0), "pool not exists" ); if (assets[i] == address(0)) { underlyingToLoanPool[loanPoolToUnderlying[pools[i]]] = address( 0 ); loanPoolToUnderlying[pools[i]] = address(0); loanPoolsSet.removeAddress(pools[i]); } else { loanPoolToUnderlying[pools[i]] = assets[i]; underlyingToLoanPool[assets[i]] = pools[i]; loanPoolsSet.addAddress(pools[i]); } emit SetLoanPool(msg.sender, pools[i], assets[i]); } } function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles ) external onlyOwner { require(addrs.length == toggles.length, "count mismatch"); for (uint256 i = 0; i < addrs.length; i++) { supportedTokens[addrs[i]] = toggles[i]; emit SetSupportedTokens(msg.sender, addrs[i], toggles[i]); } } function setLendingFeePercent(uint256 newValue) external onlyOwner { require(newValue <= 10**20, "value too high"); uint256 oldValue = lendingFeePercent; lendingFeePercent = newValue; emit SetLendingFeePercent(msg.sender, oldValue, newValue); } function setTradingFeePercent(uint256 newValue) external onlyOwner { require(newValue <= 10**20, "value too high"); uint256 oldValue = tradingFeePercent; tradingFeePercent = newValue; emit SetTradingFeePercent(msg.sender, oldValue, newValue); } function setBorrowingFeePercent(uint256 newValue) external onlyOwner { require(newValue <= 10**20, "value too high"); uint256 oldValue = borrowingFeePercent; borrowingFeePercent = newValue; emit SetBorrowingFeePercent(msg.sender, oldValue, newValue); } function setAffiliateFeePercent(uint256 newValue) external onlyOwner { require(newValue <= 10**20, "value too high"); uint256 oldValue = affiliateFeePercent; affiliateFeePercent = newValue; emit SetAffiliateFeePercent(msg.sender, oldValue, newValue); } function setLiquidationIncentivePercent(uint256 newValue) external onlyOwner { require(newValue <= 10**20, "value too high"); uint256 oldValue = liquidationIncentivePercent; liquidationIncentivePercent = newValue; emit SetLiquidationIncentivePercent(msg.sender, oldValue, newValue); } function setMaxDisagreement(uint256 newValue) external onlyOwner { maxDisagreement = newValue; } function setSourceBuffer(uint256 newValue) external onlyOwner { sourceBuffer = newValue; } function setMaxSwapSize(uint256 newValue) external onlyOwner { uint256 oldValue = maxSwapSize; maxSwapSize = newValue; emit SetMaxSwapSize(msg.sender, oldValue, newValue); } function setFeesController(address newController) external onlyOwner { address oldController = feesController; feesController = newController; emit SetFeesController(msg.sender, oldController, newController); } function withdrawLendingFees( address token, address receiver, uint256 amount ) external returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = lendingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } lendingFeeTokensHeld[token] = balance.sub(withdrawAmount); lendingFeeTokensPaid[token] = lendingFeeTokensPaid[token].add( withdrawAmount ); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawLendingFees(msg.sender, token, receiver, withdrawAmount); return true; } function withdrawTradingFees( address token, address receiver, uint256 amount ) external returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = tradingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } tradingFeeTokensHeld[token] = balance.sub(withdrawAmount); tradingFeeTokensPaid[token] = tradingFeeTokensPaid[token].add( withdrawAmount ); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawTradingFees(msg.sender, token, receiver, withdrawAmount); return true; } function withdrawBorrowingFees( address token, address receiver, uint256 amount ) external returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = borrowingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } borrowingFeeTokensHeld[token] = balance.sub(withdrawAmount); borrowingFeeTokensPaid[token] = borrowingFeeTokensPaid[token].add( withdrawAmount ); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawBorrowingFees(msg.sender, token, receiver, withdrawAmount); return true; } function withdrawProtocolToken(address receiver, uint256 amount) external onlyOwner returns (address, bool) { return _withdrawProtocolToken(receiver, amount); } function depositProtocolToken(uint256 amount) external onlyOwner { protocolTokenHeld = protocolTokenHeld.add(amount); IERC20(protocolTokenAddress).safeTransferFrom( msg.sender, address(this), amount ); } function getLoanPoolsList(uint256 start, uint256 count) external view returns (bytes32[] memory) { return loanPoolsSet.enumerate(start, count); } function isLoanPool(address loanPool) external view returns (bool) { return loanPoolToUnderlying[loanPool] != address(0); } /** * sets the contract registry address of the SovrynSwap network * @param registryAddress the address of the registry contract * */ function setSovrynSwapContractRegistryAddress(address registryAddress) external onlyOwner { require( Address.isContract(registryAddress), "registryAddress not a contract" ); address oldSovrynSwapContractRegistryAddress = sovrynSwapContractRegistryAddress; sovrynSwapContractRegistryAddress = registryAddress; emit SetSovrynSwapContractRegistryAddress( msg.sender, oldSovrynSwapContractRegistryAddress, sovrynSwapContractRegistryAddress ); } function setWrbtcToken(address wrbtcTokenAddress) external onlyOwner { require( Address.isContract(wrbtcTokenAddress), "wrbtcTokenAddress not a contract" ); address oldwrbtcToken = address(wrbtcToken); wrbtcToken = IWrbtcERC20(wrbtcTokenAddress); emit SetWrbtcToken(msg.sender, oldwrbtcToken, wrbtcTokenAddress); } function setProtocolTokenAddress(address _protocolTokenAddress) external onlyOwner { require( Address.isContract(_protocolTokenAddress), "_protocolTokenAddress not a contract" ); address oldProtocolTokenAddress = protocolTokenAddress; protocolTokenAddress = _protocolTokenAddress; emit SetProtocolTokenAddress( msg.sender, oldProtocolTokenAddress, _protocolTokenAddress ); } /** * @dev set rollover base reward. It should be denominated in wRBTC */ function setRolloverBaseReward(uint256 baseRewardValue) external onlyOwner { require(baseRewardValue > 0, "Base reward is zero"); uint256 oldValue = rolloverBaseReward; rolloverBaseReward = baseRewardValue; emit SetRolloverBaseReward(msg.sender, oldValue, rolloverBaseReward); } function setRebatePercent(uint256 rebatePercent) external onlyOwner { require(rebatePercent <= 10**20, "Fee rebate is too high"); uint256 oldRebatePercent = feeRebatePercent; feeRebatePercent = rebatePercent; emit SetRebatePercent(msg.sender, oldRebatePercent, rebatePercent); } }
set rollover base reward. It should be denominated in wRBTC/
function setRolloverBaseReward(uint256 baseRewardValue) external onlyOwner { require(baseRewardValue > 0, "Base reward is zero"); uint256 oldValue = rolloverBaseReward; rolloverBaseReward = baseRewardValue; emit SetRolloverBaseReward(msg.sender, oldValue, rolloverBaseReward); }
12,578,912
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC721A.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /* ████████╗██████╗░░█████╗░██████╗░███╗░░░███╗░█████╗░███╗░░██╗██╗░░██╗██╗███████╗ ╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗████╗░████║██╔══██╗████╗░██║██║░██╔╝██║██╔════╝ ░░░██║░░░██████╔╝███████║██████╔╝██╔████╔██║██║░░██║██╔██╗██║█████═╝░██║█████╗░░ ░░░██║░░░██╔══██╗██╔══██║██╔═══╝░██║╚██╔╝██║██║░░██║██║╚████║██╔═██╗░██║██╔══╝░░ ░░░██║░░░██║░░██║██║░░██║██║░░░░░██║░╚═╝░██║╚█████╔╝██║░╚███║██║░╚██╗██║███████╗ ░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝╚═╝╚══════╝ */ contract TrapMonkie8888 is ERC721A, Ownable, ReentrancyGuard { using Strings for uint256; // ======== SUPPLY ======== uint256 public constant MAX_SUPPLY = 8888; // ======== MAX MINTS ======== uint256 public maxPremintGenesisMob = 4; uint256 public maxPremintMutant = 3; uint256 public maxPremintOG = 2; uint256 public maxPremintTraplist = 1; uint256 public maxPublicSaleMint = 10; // ======== PRICE & TIME ======== struct SaleConfig { uint32 PremintTime; uint32 PublicTime; uint32 GenesisMobTime; uint256 PremintGenesisMobPrice; uint256 PremintMutantPrice; uint256 PremintOGPrice; uint256 PremintTraplistPrice; uint256 publicPrice; } SaleConfig public saleConfig; // ======== METADATA ======== string private uriPrefix = ''; string private uriSuffix = '.json'; string private hiddenMetadataUri; bool public revealed = false; // ======== MERKLE ROOT ======== bytes32 public GenesisMobMerkleRoot; bytes32 public MutantMerkleRoot; bytes32 public OGMerkleRoot; bytes32 public TraplistMerkleRoot; // ======== MINTED ======== mapping(address => uint256) public PremintGenesisMobMinted; mapping(address => uint256) public PremintMutantMinted; mapping(address => uint256) public PremintOGMinted; mapping(address => uint256) public PremintTraplistMinted; mapping(address => uint256) public PublicMinted; // ======== CONSTRUCTOR ======== constructor(string memory _hiddenMetadataUri) ERC721A("TrapMonkie", "TM") {} // Modifier modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } // ======== MINTING ======== /** * GENESIS/MOB MINT */ function PremintGenesisMob(uint256 _quantity, bytes32[] calldata _proof) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(saleConfig.PremintGenesisMobPrice); uint256 GenesisMobTime = uint256(config.GenesisMobTime); require(isGenesisMOBOn(price, GenesisMobTime),"Minting for Genesis/MOB has not yet begun."); bytes32 sender = keccak256(abi.encodePacked(msg.sender)); bool isValidProof = MerkleProof.verify(_proof, GenesisMobMerkleRoot, sender); require(isValidProof, "INVALID PROOF"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Claim amount exceeds collection size" ); require(PremintGenesisMobMinted[msg.sender] + _quantity <= maxPremintGenesisMob , "Exceeded claim limit"); require(price * _quantity == msg.value, "Incorrect ETH Amount Submitted"); PremintGenesisMobMinted[msg.sender] += _quantity; _safeMint(msg.sender, _quantity); } /** * MUTANT MINT */ function PremintMutant(uint256 _quantity, bytes32[] calldata _proof) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(saleConfig.PremintMutantPrice); uint256 PremintTime = uint256(config.PremintTime); require(isPremintOn(price, PremintTime),"Minting for Mutants has not yet begun."); bytes32 sender = keccak256(abi.encodePacked(msg.sender)); bool isValidProof = MerkleProof.verify(_proof, MutantMerkleRoot, sender); require(isValidProof, "INVALID PROOF"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Claim amount exceeds collection size" ); require(PremintMutantMinted[msg.sender] + _quantity <= maxPremintMutant , "Exceeded claim limit"); require(price * _quantity == msg.value, "Incorrect ETH Amount Submitted"); PremintMutantMinted[msg.sender] += _quantity; _safeMint(msg.sender, _quantity); } /** * OG MINT */ function PremintOG(uint256 _quantity, bytes32[] calldata _proof) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(saleConfig.PremintOGPrice); uint256 PremintTime = uint256(config.PremintTime); require(isPremintOn(price, PremintTime),"Minting for OG has not yet begun."); bytes32 sender = keccak256(abi.encodePacked(msg.sender)); bool isValidProof = MerkleProof.verify(_proof, OGMerkleRoot, sender); require(isValidProof, "INVALID PROOF"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Claim amount exceeds collection size" ); require(PremintOGMinted[msg.sender] + _quantity <= maxPremintOG , "Exceeded claim limit"); require(price * _quantity == msg.value, "Incorrect ETH Amount Submitted"); PremintOGMinted[msg.sender] += _quantity; _safeMint(msg.sender, _quantity); } /** * TRAPLIST MINT */ function PremintTraplist(uint256 _quantity, bytes32[] calldata _proof) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(saleConfig.PremintTraplistPrice); uint256 PremintTime = uint256(config.PremintTime); require(isPremintOn(price, PremintTime),"Minting for Traplist has not yet begun."); bytes32 sender = keccak256(abi.encodePacked(msg.sender)); bool isValidProof = MerkleProof.verify(_proof, TraplistMerkleRoot, sender); require(isValidProof, "INVALID PROOF"); require(totalSupply() + _quantity <= MAX_SUPPLY, "Claim amount exceeds collection size" ); require(PremintTraplistMinted[msg.sender] + _quantity <= maxPremintTraplist , "Exceeded claim limit"); require(price * _quantity == msg.value, "Incorrect ETH Amount Submitted"); PremintTraplistMinted[msg.sender] += _quantity; _safeMint(msg.sender, _quantity); } /** * PUBLIC MINT */ function publicMint(uint256 _quantity) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(saleConfig.publicPrice); uint256 PublicTime = uint256(config.PublicTime); require(isPublicOn(price, PublicTime),"Minting for public has not yet begun."); require(totalSupply() + _quantity <= MAX_SUPPLY, "Claim amount exceeds collection size" ); require(PublicMinted[msg.sender] + _quantity <= maxPublicSaleMint , "Exceeded claim limit"); require(price * _quantity == msg.value, "Incorrect ETH Amount Submitted"); PublicMinted[msg.sender] += _quantity; _safeMint(msg.sender, _quantity); } // ======== MERKLE ROOT SETTERS ======== /** * Set GENESIS/MOB merkle root */ function setGenesisMobMerkleRoot(bytes32 _merkleRoot) external onlyOwner { GenesisMobMerkleRoot = _merkleRoot; } /** * Set MUTANT merkle root */ function setMutantMerkleRoot(bytes32 _merkleRoot) external onlyOwner { MutantMerkleRoot = _merkleRoot; } /** * Set OG merkle root */ function setOGMerkleRoot(bytes32 _merkleRoot) external onlyOwner { OGMerkleRoot = _merkleRoot; } /** * Det TRAPLIST merkle root */ function setTraplistMerkleRoot(bytes32 _merkleRoot) external onlyOwner { TraplistMerkleRoot = _merkleRoot; } //======== MINT STATUS ======== // PUBLIC SALE function isPublicOn( uint256 publicPriceWei, uint256 PublicTime ) public view returns (bool) { return publicPriceWei != 0 && block.timestamp >= PublicTime; } // PREMINT SALE function isPremintOn( uint256 publicPriceWei, uint256 PremintTime ) public view returns (bool) { return publicPriceWei != 0 && block.timestamp >= PremintTime; } // GENESIS/MOB function isGenesisMOBOn( uint256 publicPriceWei, uint256 GenesisMobTime ) public view returns (bool) { return publicPriceWei != 0 && block.timestamp >= GenesisMobTime; } // ======== METADATA URI ======== /** * set startTokenId to 1 */ function _startTokenId() internal view virtual override(ERC721A) returns (uint256) { return 1; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ''; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } // ======== MINT SETUP ======== function SetupSaleInfo( uint32 PremintTime, uint32 PublicTime, uint32 GenesisMobTime, uint256 PremintGenesisMobPriceWei, uint256 PremintMutantPriceWei, uint256 PremintOGPriceWei, uint256 PremintTraplistPriceWei, uint256 publicPriceWei ) external onlyOwner { saleConfig = SaleConfig( PremintTime, PublicTime, GenesisMobTime, PremintGenesisMobPriceWei, PremintMutantPriceWei, PremintOGPriceWei, PremintTraplistPriceWei, publicPriceWei ); } function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } // ======== WITHDRAW ======== //ADDRESS LIST - GNOSIS VAULT % IS INCLUDED IN FOUNDER address FOUNDER_WALLET = 0xEbB31f4e2A1CdE56A59bFEA5F225aC10426a914b; address MARKETING_WALLET = 0x5cA6930006A3069a60AA88e8B0E992609f93e394; address DEVELOPER_1_WALLET = 0xeB25d89C262b9B850EF442a6E7065fE240106A51; address LEAD_ARTIST_WALLET = 0x70D5c23F4E410B76284CF8B7F1c65e0d7c79015D; address ARTIST_1_WALLET = 0x74DeF6d79DA09d94D3971FA60a22bd8D11534dAc; address ARTIST_2_WALLET = 0x5610B0AfA7586B9156848D728a64BD8Fbdb7DE96; address DEVELOPER_B_WALLET = 0x5f22a3002b96061f02f0B8921298457AD336BA3E; // FULL WITHDRAW function withdraw() public onlyOwner nonReentrant { uint256 balance = address(this).balance; require(balance > 0, "NO FUNDS AVAILABLE"); payable(FOUNDER_WALLET).transfer((balance * 52)/100); payable(MARKETING_WALLET).transfer((balance * 12)/100); payable(DEVELOPER_1_WALLET).transfer((balance * 12)/100); payable(LEAD_ARTIST_WALLET).transfer((balance * 10)/100); payable(ARTIST_1_WALLET).transfer((balance * 5)/100); payable(ARTIST_2_WALLET).transfer((balance * 5)/100); payable(DEVELOPER_B_WALLET).transfer((balance * 4)/100); } // PARTIAL WITHDRAW function withdrawAmount(uint256 _amount) public onlyOwner nonReentrant { uint256 balance = address(this).balance; require(balance > 0, "NO FUNDS AVAILABLE"); payable(FOUNDER_WALLET).transfer((_amount * 52)/100); payable(MARKETING_WALLET).transfer((_amount * 12)/100); payable(DEVELOPER_1_WALLET).transfer((_amount * 12)/100); payable(LEAD_ARTIST_WALLET).transfer((_amount * 10)/100); payable(ARTIST_1_WALLET).transfer((_amount * 5)/100); payable(ARTIST_2_WALLET).transfer((_amount * 5)/100); payable(DEVELOPER_B_WALLET).transfer((_amount * 4)/100); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Det TRAPLIST merkle root/
function setTraplistMerkleRoot(bytes32 _merkleRoot) external onlyOwner { TraplistMerkleRoot = _merkleRoot; }
1,536,873
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IArchRouterImmutableState.sol'; /// @title Immutable state /// @notice Immutable state used by periphery contracts abstract contract ArchRouterImmutableState is IArchRouterImmutableState { /// @inheritdoc IArchRouterImmutableState address public immutable override uniV3Factory; /// @inheritdoc IArchRouterImmutableState address public immutable override WETH; constructor(address _uniV3Factory, address _WETH) { uniV3Factory = _uniV3Factory; WETH = _WETH; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Copyright 2021 Archer DAO: Chris Piatt ([email protected]). */ import './interfaces/IERC20Extended.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IUniswapV3Pool.sol'; import './interfaces/IUniV3Router.sol'; import './interfaces/IWETH.sol'; import './lib/RouteLib.sol'; import './lib/TransferHelper.sol'; import './lib/SafeCast.sol'; import './lib/Path.sol'; import './lib/CallbackValidation.sol'; import './ArchRouterImmutableState.sol'; import './PaymentsWithFee.sol'; import './Multicall.sol'; import './SelfPermit.sol'; /** * @title ArcherSwapRouter * @dev Allows Uniswap V2/V3 Router-compliant trades to be paid via tips instead of gas */ contract ArcherSwapRouter is IUniV3Router, ArchRouterImmutableState, PaymentsWithFee, Multicall, SelfPermit { using Path for bytes; using SafeCast for uint256; /// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap /// can never actually be this value uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max; /// @dev Transient storage variable used for returning the computed amount in for an exact output swap. uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Trade details struct Trade { uint amountIn; uint amountOut; address[] path; address payable to; uint256 deadline; } /// @notice Uniswap V3 Swap Callback struct SwapCallbackData { bytes path; address payer; } /** * @notice Construct new ArcherSwap Router * @param _uniV3Factory Uni V3 Factory address * @param _WETH WETH address */ constructor(address _uniV3Factory, address _WETH) ArchRouterImmutableState(_uniV3Factory, _WETH) {} /** * @notice Swap tokens for ETH and pay amount of ETH as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapExactTokensForETHAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn ); _exactInputSwap(factory, trade.path, address(this)); uint256 amountOut = IWETH(WETH).balanceOf(address(this)); require(amountOut >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); tip(tipAmount); TransferHelper.safeTransferETH(trade.to, amountOut - tipAmount); } /** * @notice Swap tokens for ETH and pay amount of ETH as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapTokensForExactETHAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH'); uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path); require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0] ); _exactOutputSwap(factory, amounts, trade.path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); tip(tipAmount); TransferHelper.safeTransferETH(trade.to, trade.amountOut - tipAmount); } /** * @notice Swap ETH for tokens and pay % of ETH input as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param tipAmount amount of ETH to pay as tip */ function swapExactETHForTokensAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { tip(tipAmount); require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH'); uint256 inputAmount = msg.value - tipAmount; IWETH(WETH).deposit{value: inputAmount}(); assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), inputAmount)); uint256 balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to); _exactInputSwap(factory, trade.path, trade.to); require( IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @notice Swap ETH for tokens and pay amount of ETH input as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param tipAmount amount of ETH to pay as tip */ function swapETHForExactTokensAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { tip(tipAmount); require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH'); uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path); uint256 inputAmount = msg.value - tipAmount; require(amounts[0] <= inputAmount, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0])); _exactOutputSwap(factory, amounts, trade.path, trade.to); if (inputAmount > amounts[0]) { TransferHelper.safeTransferETH(msg.sender, inputAmount - amounts[0]); } } /** * @notice Swap tokens for tokens and pay ETH amount as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapExactTokensForTokensAndTipAmount( address factory, Trade calldata trade ) external payable { tip(msg.value); _swapExactTokensForTokens(factory, trade); } /** * @notice Swap tokens for tokens and pay % of tokens as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param pathToEth Path to ETH for tip * @param tipPct % of resulting tokens to pay as tip */ function swapExactTokensForTokensAndTipPct( address factory, Trade calldata trade, address[] calldata pathToEth, uint32 tipPct ) external payable { _swapExactTokensForTokens(factory, trade); IERC20Extended toToken = IERC20Extended(pathToEth[0]); uint256 contractTokenBalance = toToken.balanceOf(address(this)); uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000; TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount); _tipWithTokens(factory, pathToEth); } /** * @notice Swap tokens for tokens and pay ETH amount as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapTokensForExactTokensAndTipAmount( address factory, Trade calldata trade ) external payable { tip(msg.value); _swapTokensForExactTokens(factory, trade); } /** * @notice Swap tokens for tokens and pay % of tokens as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param pathToEth Path to ETH for tip * @param tipPct % of resulting tokens to pay as tip */ function swapTokensForExactTokensAndTipPct( address factory, Trade calldata trade, address[] calldata pathToEth, uint32 tipPct ) external payable { _swapTokensForExactTokens(factory, trade); IERC20Extended toToken = IERC20Extended(pathToEth[0]); uint256 contractTokenBalance = toToken.balanceOf(address(this)); uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000; TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount); _tipWithTokens(factory, pathToEth); } /** * @notice Returns the pool for the given token pair and fee. The pool contract may or may not exist. * @param tokenA First token * @param tokenB Second token * @param fee Pool fee * @return Uniswap V3 Pool */ function getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(RouteLib.computeAddress(uniV3Factory, RouteLib.getPoolKey(tokenA, tokenB, fee))); } /** * @notice Uniswap V3 Callback function that validates and pays for trade * @dev Called by Uni V3 pool contract * @param amount0Delta Delta for token 0 * @param amount1Delta Delta for token 1 * @param _data Swap callback data */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data ) external override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); CallbackValidation.verifyCallback(uniV3Factory, tokenIn, tokenOut, fee); (bool isExactInput, uint256 amountToPay) = amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta)); if (isExactInput) { pay(tokenIn, data.payer, msg.sender, amountToPay); } else { // either initiate the next swap or pay if (data.path.hasMultiplePools()) { data.path = data.path.skipToken(); _exactOutputInternal(amountToPay, msg.sender, 0, data); } else { amountInCached = amountToPay; tokenIn = tokenOut; // swap in/out because exact output swaps are reversed pay(tokenIn, data.payer, msg.sender, amountToPay); } } } /// @inheritdoc IUniV3Router function exactInputSingle(ExactInputSingleParams calldata params) public payable override returns (uint256 amountOut) { amountOut = _exactInputInternal( params.amountIn, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender}) ); require(amountOut >= params.amountOutMinimum, 'Too little received'); } /** * @notice Performs a single exact input Uni V3 swap and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactInputSingleAndTipAmount(ExactInputSingleParams calldata params, uint256 tipAmount) external payable returns (uint256 amountOut) { amountOut = exactInputSingle(params); tip(tipAmount); } /// @inheritdoc IUniV3Router function exactInput(ExactInputParams memory params) public payable override returns (uint256 amountOut) { address payer = msg.sender; // msg.sender pays for the first hop while (true) { bool hasMultiplePools = params.path.hasMultiplePools(); // the outputs of prior swaps become the inputs to subsequent ones params.amountIn = _exactInputInternal( params.amountIn, hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies 0, SwapCallbackData({ path: params.path.getFirstPool(), // only the first pool in the path is necessary payer: payer }) ); // decide whether to continue or terminate if (hasMultiplePools) { payer = address(this); // at this point, the caller has paid params.path = params.path.skipToken(); } else { amountOut = params.amountIn; break; } } require(amountOut >= params.amountOutMinimum, 'Too little received'); } /** * @notice Performs multiple exact input Uni V3 swaps and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactInputAndTipAmount(ExactInputParams calldata params, uint256 tipAmount) external payable returns (uint256 amountOut) { amountOut = exactInput(params); tip(tipAmount); } /// @inheritdoc IUniV3Router function exactOutputSingle(ExactOutputSingleParams calldata params) public payable override returns (uint256 amountIn) { // avoid an SLOAD by using the swap return data amountIn = _exactOutputInternal( params.amountOut, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender}) ); require(amountIn <= params.amountInMaximum, 'Too much requested'); // has to be reset even though we don't use it in the single hop case amountInCached = DEFAULT_AMOUNT_IN_CACHED; } /** * @notice Performs an exact output Uni V3 swap and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactOutputSingleAndTipAmount(ExactOutputSingleParams calldata params, uint256 tipAmount) external payable returns (uint256 amountIn) { amountIn = exactOutputSingle(params); tip(tipAmount); } /// @inheritdoc IUniV3Router function exactOutput(ExactOutputParams calldata params) public payable override returns (uint256 amountIn) { // it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output // swap, which happens first, and subsequent swaps are paid for within nested callback frames _exactOutputInternal( params.amountOut, params.recipient, 0, SwapCallbackData({path: params.path, payer: msg.sender}) ); amountIn = amountInCached; require(amountIn <= params.amountInMaximum, 'Too much requested'); amountInCached = DEFAULT_AMOUNT_IN_CACHED; } /** * @notice Performs multiple exact output Uni V3 swaps and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactOutputAndTipAmount(ExactOutputParams calldata params, uint256 tipAmount) external payable returns (uint256 amountIn) { amountIn = exactOutput(params); tip(tipAmount); } /** * @notice Performs a single exact input Uni V3 swap * @param amountIn Amount of input token * @param recipient Recipient of swap result * @param sqrtPriceLimitX96 Price limit * @param data Swap callback data */ function _exactInputInternal( uint256 amountIn, address recipient, uint160 sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256 amountOut) { // allow swapping to the router address with address 0 if (recipient == address(0)) recipient = address(this); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); bool zeroForOne = tokenIn < tokenOut; (int256 amount0, int256 amount1) = getPool(tokenIn, tokenOut, fee).swap( recipient, zeroForOne, amountIn.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encode(data) ); return uint256(-(zeroForOne ? amount1 : amount0)); } /** * @notice Performs a single exact output Uni V3 swap * @param amountOut Amount of output token * @param recipient Recipient of swap result * @param sqrtPriceLimitX96 Price limit * @param data Swap callback data */ function _exactOutputInternal( uint256 amountOut, address recipient, uint160 sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256 amountIn) { // allow swapping to the router address with address 0 if (recipient == address(0)) recipient = address(this); (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool(); bool zeroForOne = tokenIn < tokenOut; (int256 amount0Delta, int256 amount1Delta) = getPool(tokenIn, tokenOut, fee).swap( recipient, zeroForOne, -amountOut.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encode(data) ); uint256 amountOutReceived; (amountIn, amountOutReceived) = zeroForOne ? (uint256(amount0Delta), uint256(-amount1Delta)) : (uint256(amount1Delta), uint256(-amount0Delta)); // it's technically possible to not receive the full output amount, // so if no price limit has been specified, require this possibility away if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut); } /** * @notice Internal implementation of swap tokens for tokens * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function _swapExactTokensForTokens( address factory, Trade calldata trade ) internal { TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn ); uint balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to); _exactInputSwap(factory, trade.path, trade.to); require( IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @notice Internal implementation of swap tokens for tokens * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function _swapTokensForExactTokens( address factory, Trade calldata trade ) internal { uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path); require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0] ); _exactOutputSwap(factory, amounts, trade.path, trade.to); } /** * @notice Internal implementation of exact input Uni V2/Sushi swap * @param factory Uniswap V2-compliant Factory contract * @param path Trade path * @param _to Trade recipient */ function _exactInputSwap( address factory, address[] memory path, address _to ) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = RouteLib.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(RouteLib.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Extended(input).balanceOf(address(pair)) - reserveInput; amountOutput = RouteLib.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /** * @notice Internal implementation of exact output Uni V2/Sushi swap * @param factory Uniswap V2-compliant Factory contract * @param amounts Output amounts * @param path Trade path * @param _to Trade recipient */ function _exactOutputSwap( address factory, uint[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = RouteLib.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(RouteLib.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } /** * @notice Convert a token balance into ETH and then tip * @param factory Factory address * @param path Path for swap */ function _tipWithTokens( address factory, address[] memory path ) internal { _exactInputSwap(factory, path, address(this)); uint256 amountOut = IWETH(WETH).balanceOf(address(this)); IWETH(WETH).withdraw(amountOut); tip(address(this).balance); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IERC20Extended.sol'; import './interfaces/IPayments.sol'; import './interfaces/IWETH.sol'; import './lib/TransferHelper.sol'; import './ArchRouterImmutableState.sol'; abstract contract Payments is IPayments, ArchRouterImmutableState { receive() external payable { require(msg.sender == WETH, 'Not WETH'); } /// @inheritdoc IPayments function unwrapWETH(uint256 amountMinimum, address recipient) external payable override { uint256 balanceWETH = withdrawWETH(amountMinimum); TransferHelper.safeTransferETH(recipient, balanceWETH); } /// @inheritdoc IPayments function unwrapWETHAndTip(uint256 tipAmount, uint256 amountMinimum, address recipient) external payable override { uint256 balanceWETH = withdrawWETH(amountMinimum); tip(tipAmount); if(balanceWETH > tipAmount) { TransferHelper.safeTransferETH(recipient, balanceWETH - tipAmount); } } /// @inheritdoc IPayments function tip(uint256 tipAmount) public payable override { TransferHelper.safeTransferETH(block.coinbase, tipAmount); } /// @inheritdoc IPayments function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable override { uint256 balanceToken = IERC20Extended(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { TransferHelper.safeTransfer(token, recipient, balanceToken); } } /// @inheritdoc IPayments function refundETH() external payable override { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); } /// @param amountMinimum Min amount of WETH to withdraw function withdrawWETH(uint256 amountMinimum) public returns(uint256 balanceWETH){ balanceWETH = IWETH(WETH).balanceOf(address(this)); require(balanceWETH >= amountMinimum && balanceWETH > 0, 'Insufficient WETH'); IWETH(WETH).withdraw(balanceWETH); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == WETH && address(this).balance >= value) { // pay with WETH IWETH(WETH).deposit{value: value}(); // wrap only what is needed to pay IWETH(WETH).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IERC20Extended.sol'; import './interfaces/IPaymentsWithFee.sol'; import './interfaces/IWETH.sol'; import './lib/TransferHelper.sol'; import './Payments.sol'; abstract contract PaymentsWithFee is Payments, IPaymentsWithFee { /// @inheritdoc IPaymentsWithFee function unwrapWETHWithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceWETH = IWETH(WETH).balanceOf(address(this)); require(balanceWETH >= amountMinimum, 'Insufficient WETH'); if (balanceWETH > 0) { IWETH(WETH).withdraw(balanceWETH); uint256 feeAmount = (balanceWETH * feeBips) / 10_000; if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount); TransferHelper.safeTransferETH(recipient, balanceWETH - feeAmount); } } /// @inheritdoc IPaymentsWithFee function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceToken = IERC20Extended(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { uint256 feeAmount = (balanceToken * feeBips) / 10_000; if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount); TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IERC20Extended.sol'; import './interfaces/ISelfPermit.sol'; import './interfaces/IERC20PermitAllowed.sol'; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route /// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function /// that requires an approval in a single transaction. abstract contract SelfPermit is ISelfPermit { /// @inheritdoc ISelfPermit function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Extended(token).permit(msg.sender, address(this), value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20Extended(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20Extended(token).allowance(msg.sender, address(this)) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IArchRouterImmutableState { /// @return Returns the address of the Uniswap V3 factory function uniV3Factory() external view returns (address); /// @return Returns the address of WETH function WETH() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20Extended { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function version() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function nonces(address) external view returns (uint); function getDomainSeparator() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Interface for permit /// @notice Interface used by DAI/CHAI for permit interface IERC20PermitAllowed { /// @notice Approve the spender to spend some tokens via the holder signature /// @dev This is the permit interface used by DAI and CHAI /// @param holder The address of the token holder, the token owner /// @param spender The address of the token spender /// @param nonce The holder's nonce, increases at each call to permit /// @param expiry The timestamp at which the permit is no longer valid /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0 /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Multicall interface /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @dev The `msg.value` should not be trusted for any method callable from multicall. /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPayments { /// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users. /// @param amountMinimum The minimum amount of WETH to unwrap /// @param recipient The address receiving ETH function unwrapWETH(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; /// @notice Tips miners using the WETH balance in the contract and then transfers the remainder to recipient /// @dev The recipientMinimum parameter prevents malicious contracts from stealing the ETH from users /// @param tipAmount Tip amount /// @param amountMinimum The minimum amount of WETH to withdraw /// @param recipient The destination address of the ETH left after tipping function unwrapWETHAndTip( uint256 tipAmount, uint256 amountMinimum, address recipient ) external payable; /// @notice Tips miners using the ETH balance in the contract + msg.value /// @param tipAmount Tip amount function tip( uint256 tipAmount ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './IPayments.sol'; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPaymentsWithFee is IPayments { /// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH, with a percentage between /// 0 (exclusive), and 1 (inclusive) going to feeRecipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users. function unwrapWETHWithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) external payable; /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between /// 0 (exclusive) and 1 (inclusive) going to feeRecipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route interface ISelfPermit { /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed. /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniV3Router is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool { /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity ^0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import '../interfaces/IUniswapV3Pool.sol'; import './RouteLib.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, RouteLib.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, RouteLib.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(RouteLib.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../interfaces/IUniswapV2Pair.sol'; library RouteLib { address internal constant _SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; bytes32 internal constant _SUSHI_ROUTER_INIT_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; bytes32 internal constant _UNI_V2_ROUTER_INIT_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; bytes32 internal constant _UNI_V3_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'RouteLib: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'RouteLib: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); bytes32 initHash = factory == _SUSHI_FACTORY ? _SUSHI_ROUTER_INIT_HASH : _UNI_V2_ROUTER_INIT_HASH; pair = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initHash // init code hash ) ) ) ) ); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), _UNI_V3_INIT_CODE_HASH ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'RouteLib: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY'); amountB = amountA * (reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'RouteLib: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn * 997; uint numerator = amountInWithFee * reserveOut; uint denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'RouteLib: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn * amountOut * 1000; uint denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'RouteLib: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'RouteLib: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } }
Performs an exact output Uni V3 swap and tips an amount of ETH params Swap params tipAmount Tip amount/
function exactOutputSingleAndTipAmount(ExactOutputSingleParams calldata params, uint256 tipAmount) external payable returns (uint256 amountIn) { amountIn = exactOutputSingle(params); tip(tipAmount); }
11,683,082
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // Langue de compilation pragma experimental ABIEncoderV2; // Encoder pour éviter les bugs dans la Blockchain import "@openzeppelin/contracts/math/SafeMath.sol"; // Librairie Openzepplin de sécurisation échanges d'argents numériques /// @title Dapp de crowdfunding en Ether pour definir la structure et les fonctions de ce Smart Contract /// @author Henri-Michel LEOCADIE /// @notice Vous ne pouvez utliser ce contrat que pour faire des dépots et retour éventuel du ou des dépôts la plus basique /// @dev Tous les appels de fonction sont implémentés sans effects secondaires contract DepositCrowdfunding { /// @info code : SafeMath librairie d'Openzepplin qui sécurise tous les échanges d'argents numériques /// dans le Blockchain using SafeMath for uint256; /// @info code : "mapping" est une variable qui permet d'associer deux variables entre elles, /// cependant ici, elle gére les adresses et les montants mapping(address => uint256) public balances; /// @info code : "Event" pour la gestion des montants versés lors du Deposit, le Withdraw et le transfert ainsi /// qu'un call pour rappeller l'adresse ou les adresses avec leurs montants. event Deposit(address sender, uint256 amount); event Withdrawal(address receiver, uint256 amount); event Transfer(address sender, address receiver, uint256 amount); /// @info code : le .add utilise bien la sécurité du SafeMath de la bibliothéque d'Openzepplin /// @info code : la fonction "deposit" est pour déposer de l'Ether dans le contrat déployer avec sa balance function deposit() public payable { emit Deposit(msg.sender, msg.value); balances[msg.sender] = balances[msg.sender].add(msg.value); } /// @info code : la fonction "withdraw" est pour rembourser simplement à partir du Front /// @info code : le "require" est pour vérifier que l'argent est bien sur le compte avant le remboursement /// @info code : "Emit" fait un appel à "Event Withdrawal" et sa envoi à l'adresse du "receiver" un montant, ensuite la /// balance de celui qui envoie l'argent soustraire le montant puis l'envoi au "receiver" function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount, "Insufficient funds"); balances[msg.sender] = balances[msg.sender].sub(amount); emit Withdrawal(msg.sender, amount); msg.sender.transfer(amount); } /// @info code : le .sub et le .add utilise bien la sécurité du SafeMath de la bibliothéque d'Openzepplin /// @info code : La fonction "transfer" permet d'envoyer de l'argent sur un autre compte en superAdmin pour rembourser /// de manière indépendante et dispatcher sur différentes comptes function transfer(address receiver, uint256 amount) public { require(balances[msg.sender] >= amount, "Insufficient funds"); balances[msg.sender] = balances[msg.sender].sub(amount); balances[receiver] = balances[receiver].add(amount); emit Transfer(msg.sender, receiver, amount); } /// @ info code : Développement futur de la dapp pour intégrer et mémoriser plusieurs adresses en même temps dans le Front /*function transfer(address[] memory receivers, uint amount) public { require(balances[msg.sender] >= receivers.length * amount, "Insufficient funds"); for (uint i=0; i<receivers.length; i++) { balances[msg.sender] -= amount; balances[receivers[i]] += amount; emit Transfer(msg.sender, receivers[i], amount);* } }*/ }
@info code : SafeMath librairie d'Openzepplin qui sécurise tous les échanges d'argents numériques dans le Blockchain @info code : "mapping" est une variable qui permet d'associer deux variables entre elles, cependant ici, elle gére les adresses et les montants @info code : "Event" pour la gestion des montants versés lors du Deposit, le Withdraw et le transfert ainsi qu'un call pour rappeller l'adresse ou les adresses avec leurs montants. @info code : le .add utilise bien la sécurité du SafeMath de la bibliothéque d'Openzepplin @info code : la fonction "deposit" est pour déposer de l'Ether dans le contrat déployer avec sa balance
function deposit() public payable { emit Deposit(msg.sender, msg.value); balances[msg.sender] = balances[msg.sender].add(msg.value); }
5,428,228
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../interfaces/IDeBridgeToken.sol"; contract DeBridgeToken is ERC20Upgradeable, AccessControlUpgradeable, IDeBridgeToken { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // minter role identifier bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; // transfer's counter uint8 internal _decimals; /* ========== ERRORS ========== */ error MinterBadRole(); /* ========== MODIFIERS ========== */ modifier onlyMinter() { if (!hasRole(MINTER_ROLE, msg.sender)) revert MinterBadRole(); _; } /// @dev Constructor that initializes the most important configurations. /// @param name_ Asset's name. /// @param symbol_ Asset's symbol. /// @param minters The accounts allowed to int new tokens. function initialize( string memory name_, string memory symbol_, uint8 decimals_, address admin, address[] memory minters ) public initializer { _decimals = decimals_; name_ = string(abi.encodePacked("deBridge ", bytes(name_).length == 0 ? symbol_ : name_)); symbol_ = string(abi.encodePacked("de", symbol_)); __ERC20_init(name_, symbol_); _setupRole(DEFAULT_ADMIN_ROLE, admin); for (uint256 i = 0; i < minters.length; i++) { _setupRole(MINTER_ROLE, minters[i]); } uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name_)), keccak256(bytes("1")), chainId, address(this) ) ); } /// @dev Issues new tokens. /// @param _receiver Token's receiver. /// @param _amount Amount to be minted. function mint(address _receiver, uint256 _amount) external override onlyMinter { _mint(_receiver, _amount); } /// @dev Destroys existed tokens. /// @param _amount Amount to be burnt. function burn(uint256 _amount) external override onlyMinter { _burn(msg.sender, _amount); } /// @dev Approves the spender by signature. /// @param _owner Token's owner. /// @param _spender Account to be approved. /// @param _value Amount to be approved. /// @param _deadline The permit valid until. /// @param _v Signature part. /// @param _r Signature part. /// @param _s Signature part. function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external override { require(_deadline >= block.timestamp, "permit: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _deadline ) ) ) ); address recoveredAddress = ecrecover(digest, _v, _r, _s); require( recoveredAddress != address(0) && recoveredAddress == _owner, "permit: invalid signature" ); _approve(_owner, _spender, _value); } function decimals() public view override returns (uint8) { return _decimals; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../interfaces/IERC20Permit.sol"; interface IDeBridgeToken is IERC20Upgradeable, IERC20Permit { function mint(address _receiver, uint256 _amount) external; function burn(uint256 _amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
Constructor that initializes the most important configurations. name_ Asset's name. symbol_ Asset's symbol. minters The accounts allowed to int new tokens.
function initialize( string memory name_, string memory symbol_, uint8 decimals_, address admin, address[] memory minters ) public initializer { _decimals = decimals_; name_ = string(abi.encodePacked("deBridge ", bytes(name_).length == 0 ? symbol_ : name_)); symbol_ = string(abi.encodePacked("de", symbol_)); __ERC20_init(name_, symbol_); _setupRole(DEFAULT_ADMIN_ROLE, admin); for (uint256 i = 0; i < minters.length; i++) { _setupRole(MINTER_ROLE, minters[i]); } uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name_)), keccak256(bytes("1")), chainId, address(this) ) ); }
5,973,103
pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false // Mapping to track authorized AppContracts mapping(address => bool) private authorizedCallers; // Mapping to track voters of operational status /************ All airlines ***************************************/ mapping(address => Airline) private airlines; address[] activeAirlines = new address[](0); struct Airline { address airline; bool isFunded; bool isRegistered; } struct Flight { address airline; string flight; uint256 timestamp; bool isRegistered; address[] passengers; } struct FlightInsurance { address airline; uint256 insurance; } mapping(bytes32 => Flight) flights; // All registered flights mapping(address => FlightInsurance) insurance; uint256 constant MAX_INSURANCE = 1 ether; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event InsuranceCredited( address passenger, uint256 insurance ); event AmountTransfered( address passenger, uint256 amount ); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public payable { contractOwner = msg.sender; contractOwner.transfer(msg.value); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** *@dev Modifier that check if airline mapping exists or not */ modifier requireRegisteredAirline(address airline) { require(airline != address(0), "Airline is not registered-0"); address tempAddress = airlines[airline].airline; require(tempAddress != address(0), "Airline is not registered-1"); _; } /** *@dev Modifier that check if caller is authorized */ modifier requireAuthorizedCaller(address caller) { require(authorizedCallers[caller], "Caller is not authorized"); _; } modifier requireFlightRegistered(address airline, string memory flight, uint256 timestamp) { require(isFlightRegistered(airline, flight, timestamp), "Flight does not exists"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { require(operational != mode, "Operational status should be different from current status"); operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airline ) public requireIsOperational { require(!airlines[airline].isRegistered, "Airline is already registered"); airlines[airline] = Airline(airline, false, true); activeAirlines.push(airline); //return airlines[airline].isRegistered; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fundAirline ( address airline ) public payable { // Credit airline balance airlines[airline].isFunded = true; // Transfer amount to contract address contractOwner.transfer(msg.value); } /** * Utility functions */ function authorizeCaller(address contractAddress) external requireContractOwner { authorizedCallers[contractAddress] = true; } function deAuthorizeCaller(address contractAddress) external requireContractOwner { delete authorizedCallers[contractAddress]; } /** Check if airline is present */ function isAirline(address airline) external view returns(bool) { return (airlines[airline].airline != address(0)); } /** Get Airline isFunded */ function isAirlineFunded(address airline) external view returns(bool) { if (activeAirlines.length == 0) { // let first airline pass return true; } return airlines[airline].isFunded; } /** Get Airline balance */ function getActiveAirlines() external view returns(address[] memory) { return activeAirlines; } /************ All flights ****************************************/ /** * @dev Register a future flight for insuring. * */ function registerFlight ( address airline, string flight, uint256 timestamp ) public requireIsOperational requireRegisteredAirline(airline) { bytes32 key = getFlightKey(airline, flight, timestamp); require(!flights[key].isRegistered, "Flight is already registered"); address[] memory passengers = new address[](0); flights[key] = Flight(airline, flight, timestamp, true, passengers); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( address airline, string flight, uint256 timestamp, uint8 statusCode ) external requireIsOperational requireRegisteredAirline(airline) { bytes32 key = getFlightKey(airline, flight, timestamp); address[] memory passengers = flights[key].passengers; require(passengers.length > 0, "No passenger baught insurance yet...."); for(uint8 i = 0; i < passengers.length; i++) { creditInsuree(passengers[i], airline); } } function buyInsurance ( address airline, string flight, uint256 timestamp ) external payable requireFlightRegistered(airline, flight, timestamp) { require(msg.value > 0 && msg.value <= MAX_INSURANCE, "Insurance limits not matched"); bytes32 key = getFlightKey(airline, flight, timestamp); flights[key].passengers.push(msg.sender); insurance[msg.sender] = FlightInsurance(airline, msg.value); } /** Credit insurees if flight is delay*/ function creditInsuree ( address passenger, address airline ) public requireAuthorizedCaller(msg.sender) payable { uint256 insuranceAmount = insurance[passenger].insurance; require(insuranceAmount > 0, "Passenger haven't bought insurance"); require(airline != address(0), "Airline doesn't exists"); // Apply insurance policy uint256 refundAmount = insuranceAmount.mul(15).div(10); // 1.5x insurance[passenger].insurance = insurance[passenger].insurance.add(refundAmount); emit InsuranceCredited(passenger, insurance[passenger].insurance); } /** * @dev Passengers can withdraw amount to their accounts * */ function withdraw ( address passenger, uint256 amount ) external requireAuthorizedCaller(msg.sender) payable { uint256 insuranceAmount = insurance[passenger].insurance; require(amount <= insuranceAmount, "Insufficient balance to withdraw"); // Debit first approach insurance[passenger].insurance = insurance[passenger].insurance.sub(amount); // Transfer amount to account passenger.transfer(insuranceAmount); emit AmountTransfered(passenger, insuranceAmount); } function getInsuranceAmount() public view returns (uint256){ return insurance[msg.sender].insurance; } function getContractBalance() external view returns (uint256 balance) { return contractOwner.balance; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function isFlightRegistered ( address airline, string flight, uint256 timestamp ) public view returns(bool) { bytes32 key = getFlightKey(airline, flight, timestamp); return flights[key].isRegistered; } /** * @dev Fallback function for funding smart contract. * */ function() external payable { contractOwner.transfer(msg.value); } }
Get Airline isFunded / let first airline pass
function isAirlineFunded(address airline) external view returns(bool) { if (activeAirlines.length == 0) { return true; } return airlines[airline].isFunded; }
12,659,904
// File: contracts/vaults/IStrategy.sol pragma solidity 0.5.17; interface istrategy59 { //inject NONSTANDARD NAMING function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING function WANT31() external view returns (address); //inject NONSTANDARD NAMING function WITHDRAW24(address) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/IERC20.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface ierc2080 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/ITreasury.sol pragma solidity 0.5.17; interface itreasury2 { //inject NONSTANDARD NAMING function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IVault.sol pragma solidity 0.5.17; interface ivault53 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/vaults/IVaultRewards.sol pragma solidity 0.5.17; interface ivaultrewards63 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IController.sol pragma solidity 0.5.17; interface icontroller20 { //inject NONSTANDARD NAMING function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING external view returns ( uint256 vaultRewardPercentage, uint256 hurdleAmount, uint256 harvestPercentage ); function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING function EARN37(address, uint256) external; //inject NONSTANDARD NAMING function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING } // File: contracts/ISwapRouter.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface swaprouter18 { //inject NONSTANDARD NAMING function WETH90() external pure returns (address); //inject NONSTANDARD NAMING function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/SafeMath.sol pragma solidity 0.5.17; // Note: This file has been modified to include the sqrt function for quadratic voting library math29 { //inject NONSTANDARD NAMING function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); } } library safemath85 { //inject NONSTANDARD NAMING function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB75(a, b, "SafeMath: subtraction overflow"); } function SUB75(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL41(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV62(a, b, "SafeMath: division by zero"); } function DIV62(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD3(a, b, "SafeMath: modulo by zero"); } function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/zeppelin/Address.sol pragma solidity 0.5.17; library address35 { //inject NONSTANDARD NAMING function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/zeppelin/SafeERC20.sol pragma solidity 0.5.17; library safeerc2099 { //inject NONSTANDARD NAMING using safemath85 for uint256; using address35 for address; function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value)); } function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE58(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value)); } function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/vaults/strategy/MStableStrategy.sol //SPDX-License-Identifier: MIT pragma solidity 0.5.17; interface ibpt3 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); } interface impool6 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING function EXIT39() external; //inject NONSTANDARD NAMING } interface imtagov79 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING function WITHDRAW24() external; //inject NONSTANDARD NAMING function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING } contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING using safeerc2099 for ierc2080; using address35 for address; using safemath85 for uint256; uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING uint256 public hurdleLastUpdateTime; uint256 public harvestAmountThisEpoch; uint256 public strategistCollectedFee; uint256 public numPools = 1; ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2); ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80); imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF); ierc2080 public want = usdc; // should be set only in constructor or hardcoded icontroller20 public controller; // should be set only in constructor address public strategist; // mutable, but only by strategist // want must be equal to an underlying vault token (Eg. USDC) constructor(icontroller20 _controller) public { controller = _controller; strategist = msg.sender; } function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING return "MstableStrategy"; } function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); strategist = _strategist; } function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); numPools = _numPools; } function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); for (uint i = 0; i < recipients.length; i++) { require( recipients[i] == address(musdcBpt) || recipients[i] == address(swapRouter) || recipients[i] == address(mPool) || recipients[i] == address(mtaGov), "bad recipient" ); uint256 allowance = isIncrease ? uint256(-1) : 0; token.SAFEAPPROVE5(recipients[i], allowance); } } // Assumed that caller checks against available funds in vault function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this)); require(amount <= availFunds, "exceed contAllowance"); controller.EARN37(address(this), amount); // deposit into musdcBpt uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(bptTokenAmt); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING // get balance in mPool uint256 bptStakeAmt = mPool.BALANCEOF3(address(this)); // get usdc + musd amts in BPT, and total BPT uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt)); uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt)); uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74(); // convert musd to usdc usdcAmt = usdcAmt.ADD14( musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc))) ); return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt); } function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING (uint256 earnedAmt,) = mPool.EARNED23(address(this)); return earnedAmt.ADD14(mtaGov.EARNED23(address(this))); } function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING ierc2080 erc20Token = ierc2080(token); require(msg.sender == address(controller), "!controller"); erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this))); } function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert to desired amount musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1)); // deposit whatever remaining bpt back into mPool mPool.STAKE12(musdcBpt.BALANCEOF3(address(this))); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount); } function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert reward to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; // convert bpt to want tokens musdcBpt.EXITSWAPPOOLAMOUNTIN6( address(want), musdcBpt.BALANCEOF3(address(this)), 0 ); // exclude collected strategist fee balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance); } function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING if (claimMPool) mPool.CLAIMREWARD81(); if (claimGov) mtaGov.CLAIMREWARD81(); // convert 80% reward to want tokens // in case swap fails, return (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", false ) ); // to remove compiler warning if (!success) return; uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); uint256 vaultRewardPercentage; uint256 hurdleAmount; uint256 harvestPercentage; uint256 epochTime; (vaultRewardPercentage, hurdleAmount, harvestPercentage) = controller.GETHARVESTINFO14(address(this), msg.sender); // check if harvest amount has to be reset if (hurdleLastUpdateTime < epochTime) { // reset collected amount harvestAmountThisEpoch = 0; } // update variables hurdleLastUpdateTime = block.timestamp; harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount); // first, take harvester fee uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43); want.SAFETRANSFER62(msg.sender, harvestFee); uint256 fee; // then, if hurdle amount has been exceeded, take performance fee if (harvestAmountThisEpoch >= hurdleAmount) { fee = amount.MUL41(performance_fee63).DIV62(denom43); strategistCollectedFee = strategistCollectedFee.ADD14(fee); } // do the subtraction of harvester and strategist fees amount = amount.SUB75(harvestFee).SUB75(fee); // calculate how much is to be re-invested // fee = vault reward amount, reusing variable fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43); want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee); controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee); amount = amount.SUB75(fee); // finally, use remaining want amount for reinvestment amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(amount); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING strategistCollectedFee = 0; want.SAFETRANSFER62(strategist, strategistCollectedFee); } function EXITMGOV72() external { //inject NONSTANDARD NAMING mtaGov.WITHDRAW24(); // convert to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; want.SAFETRANSFER62( address(controller.REWARDS0(address(want))), want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee) ); } function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING uint256 swapAmt = mta.BALANCEOF3(address(this)); if (swapAmt == 0) return; // do the exchange address[] memory routeDetails = new address[](3); routeDetails[0] = address(mta); routeDetails[1] = swapRouter.WETH90(); routeDetails[2] = address(want); swapRouter.SWAPEXACTTOKENSFORTOKENS91( exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43), 0, routeDetails, address(this), block.timestamp + 100 ); } function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING uint256 mtaBal = mta.BALANCEOF3(address(this)); if (mtaBal == 0) return; if (mtaGov.BALANCEOF3(address(this)) == 0) { // create lock with max time mtaGov.CREATELOCK73(mtaBal, 1632580257); } else { // increase amount mtaGov.INCREASELOCKAMOUNT91(mtaBal); } } }
inject NONSTANDARD NAMING
function WITHDRAW24(address token) external {
1,825,163
./full_match/1/0xC1810aa7F733269C39D640f240555d0A4ebF4264/sources/contracts/StrategyUniverseStaking.sol
our main trigger is regarding our DCA since there is low liquidity for $XYZ Should not trigger if Strategy is not activated Should not trigger if we haven't waited long enough since previous harvest Should trigger if hasn't been called in a while If some amount is owed, pay it back NOTE: Since debt is based on deposits, it makes sense to guard against large changes to the value from triggering a harvest directly through user behavior. This should ensure reasonable resistance to manipulation from user-initiated withdrawals as the outstanding debt fluctuates. Check for profits and losses Trigger if we have a loss to report Trigger if it's been long enough since our last harvest based on our DCA schedule. each epoch is 1 week.
function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { StrategyParams memory params = vault.strategies(address(this)); if (params.activation == 0) return false; if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; uint256 total = estimatedTotalAssets(); if (total.add(debtThreshold) < params.totalDebt) return true; uint256 week = 86400 * 7; if (block.timestamp.sub(params.lastReport) > week.div(sellsPerEpoch)) { return true; } }
4,985,211
// contracts/shareOracle.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../contracts/PriceSource.sol"; contract shareOracle { using SafeMath for uint256; // this should just be vieweing a chainlink oracle's price // then it would check the balances of that contract in the token that its checking. // it should return the price per token based on the camToken's balance PriceSource public priceSource; ERC20 public underlying; ERC20 public shares; uint256 public fallbackPrice; event FallbackPrice( uint80 roundId, int256 price, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // price Source gives underlying price per token // shareToken should hold underlying and we need to calculate a PPS constructor(address _priceSource, address _underlying, address _shares) public { priceSource = PriceSource(_priceSource); underlying = ERC20(_underlying); shares = ERC20(_shares); } // to integrate we just need to inherit that same interface the other page uses. function latestRoundData() public view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ){ // we should passthrough all the data from the chainlink call. This would allow for transparency over the information sent. // Then we can filter as needed but this could be a cool standard we use for share-based tokens (like the compounding tokens) // check how much underlying does the share contract have. // underlying.balanceOf(address(shares)) // then we check how many shares do we have outstanding // shares.totalSupply() // now we divide the total value of underlying held in the contract by the number of tokens ( uint80 roundId, int256 price, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = priceSource.latestRoundData(); uint256 _price; if(price>0){ _price=uint256(price); } else { _price=fallbackPrice; } uint256 newPrice = ((underlying.balanceOf(address(shares))).mul(_price).div(shares.totalSupply())); return(roundId, int256(newPrice), startedAt, updatedAt, answeredInRound); } function getUnderlying() public view returns (uint256, uint256) { return (underlying.balanceOf(address(shares)), shares.totalSupply()); } function updateFallbackPrice() public { ( uint80 roundId, int256 price, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = priceSource.latestRoundData(); if (price > 0) { fallbackPrice = uint256(price); emit FallbackPrice(roundId,price,startedAt,updatedAt,answeredInRound); } } }
we should passthrough all the data from the chainlink call. This would allow for transparency over the information sent. Then we can filter as needed but this could be a cool standard we use for share-based tokens (like the compounding tokens) check how much underlying does the share contract have. underlying.balanceOf(address(shares)) then we check how many shares do we have outstanding shares.totalSupply() now we divide the total value of underlying held in the contract by the number of tokens
function latestRoundData() public view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ){ ( uint80 roundId, int256 price, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = priceSource.latestRoundData(); uint256 _price; if(price>0){ _price=uint256(price); _price=fallbackPrice; } uint256 newPrice = ((underlying.balanceOf(address(shares))).mul(_price).div(shares.totalSupply())); return(roundId, int256(newPrice), startedAt, updatedAt, answeredInRound); }
12,830,635
./full_match/137/0xCbfb6507632A5d73667dEe6966042B3a430e9663/sources/contracts/LimitOrderManager/LimitOrderManager.sol
@inheritdoc ILimitOrderManager/
function getOrder(uint256 _id) external view override returns (LimitOrderLibrary.LimitOrder memory) { _require(orders[orderIndexes[_id]].id == _id, Errors.ORDER_DOES_NOT_EXIST.selector); return orders[orderIndexes[_id]]; }
4,697,938
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IUnit { function balanceOf(address _address) external view returns (uint256); function stake(address _address) external; function unstake(address _address) external; function getStakingStatus(address _address) external view returns (bool); function stakingInformation() external view returns (address, bool); } interface genericBalanceOf { function balanceOf(address _address) external view returns (uint256); } error CallerIsSmartContract(); error CallerNotOwner(); error CallerNotApprovedUnit(); error NewOwnerZeroAddress(); contract MythicalDreamlandPreSeason { struct _stakeableUnit { IUnit stakeableContract; uint256 dailyYield; uint256 baseYield; } struct _stakerData { uint128 accumulatedRewards; uint64 lastClaimTimestamp; uint64 stakedUnlockTimestamp; } struct _seasonData { bool active; uint256 startTimestamp; uint256 endTimestamp; } address internal _owner; genericBalanceOf public INHIB; genericBalanceOf public LORD; uint256 private immutable etherConversion = 1000000000000000000; uint256 public totalStakeableUnits; uint256 public lordBonus = 20; uint256 public inhibitorBonus = 10; uint256 public lockedBonus = 50; uint256 public optionalLockPeriod = 30; _seasonData public seasonData; mapping (address => bool) private _approvedUnits; mapping (address => uint256) private _stakeableUnitsLocations; mapping (uint256 => _stakeableUnit) private stakeableUnits; mapping (address => _stakerData) private stakerData; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address _inhibAddress) { _transferOwnership(_msgSender()); setInhibitor(_inhibAddress); } function _msgSender() internal view returns (address) { return msg.sender; } modifier callerIsUser() { if (tx.origin != _msgSender() || _msgSender().code.length != 0) revert CallerIsSmartContract(); _; } modifier onlyOwner() { if (owner() != _msgSender()) revert CallerNotOwner(); _; } modifier onlyApprovedUnit() { if (!_approvedUnits[_msgSender()]) revert CallerNotApprovedUnit(); _; } /** * @dev Returns the current timestamp rewards are calculated against. */ function getTimestamp() public view returns (uint256) { uint256 currentTimeStamp = block.timestamp; if (seasonData.endTimestamp == 0) return currentTimeStamp; return (currentTimeStamp > seasonData.endTimestamp ? seasonData.endTimestamp : currentTimeStamp); } /** * @dev Stakes the `caller` tokens for `_stakingContract`. If the user elects to opt into time lock, tokens will be locked for 30 days. * Requirements: * * - The season must be active. * - The `caller` must own an Inhibitor. * - The `_stakingContract` must be an approved unit. * - the tokens of `caller` must currently be unstaked. */ function stakeUnits(address _stakingContract, bool _optIntoLock) public callerIsUser { require(seasonData.active, "SeasonHasEnded"); require(INHIB.balanceOf(_msgSender()) > 0, "NoInhibitorOwned"); uint256 location = _stakeableUnitsLocations[_stakingContract]; require(location != 0, "UnknownStakeableUnit"); if (getUserIsStaked(_msgSender())) { aggregateRewards(_msgSender()); } else { stakerData[_msgSender()].lastClaimTimestamp = uint64(block.timestamp); } if (_optIntoLock) { stakerData[_msgSender()].stakedUnlockTimestamp = uint64(block.timestamp + (optionalLockPeriod * 1 days)); } if (!stakeableUnits[location].stakeableContract.getStakingStatus(_msgSender()) && stakeableUnits[location].stakeableContract.balanceOf(_msgSender()) > 0){ stakeableUnits[location].stakeableContract.stake(_msgSender()); } else { revert("NoUnitsToStake"); } } /** * @dev Unstakes the `caller` tokens for `_stakingContract`. * Requirements: * * - The tokens of `caller` must not currently be optionally locked. * - The `_stakingContract` must be an approved unit. * - the tokens of `caller` must currently be staked. */ function unstakeUnits(address _stakingContract) public callerIsUser { uint256 location = _stakeableUnitsLocations[_stakingContract]; require(location != 0, "UnknownStakeableUnit"); require(stakerData[_msgSender()].stakedUnlockTimestamp < block.timestamp, "TimeLockActive"); aggregateRewards(_msgSender()); if (stakeableUnits[location].stakeableContract.getStakingStatus(_msgSender())){ stakeableUnits[location].stakeableContract.unstake(_msgSender()); } else { revert("NoUnitsToUnstake"); } } /** * @dev Locks in rewards of `_address` for staking. * Requirements: * * - The `caller` must either be `_address` or an approved unit itself. */ function aggregateRewards(address _address) public { require (_approvedUnits[_msgSender()] || _address == _msgSender(), "CallerLacksPermissions"); uint256 rewards = getPendingRewards(_address); stakerData[_address].lastClaimTimestamp = uint64(block.timestamp); stakerData[_address].accumulatedRewards += uint128(rewards); } /** * @dev Returns the current total rewards of `_address` from staking. */ function getAccumulatedRewards(address _address) public view returns (uint256) { unchecked { return getPendingRewards(_address) + stakerData[_address].accumulatedRewards; } } /** * @dev Returns the current pending rewards of `_address` from staking. */ function getPendingRewards(address _address) public view returns (uint256) { uint256 units = totalStakeableUnits; if (units == 0) return 0; uint256 rewards; unchecked { for (uint256 i = 1; i <= units; i++){ if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){ rewards += stakeableUnits[i].stakeableContract.balanceOf(_address) * stakeableUnits[i].baseYield; } } return rewards * getTimeSinceClaimed(_address) * getStakingMultiplier(_address) / 100; } } /** * @dev Returns the time in seconds it has been since `_address` has last locked in rewards from staking. */ function getTimeSinceClaimed(address _address) public view returns (uint256) { if (stakerData[_address].lastClaimTimestamp == 0) return getTimestamp() - seasonData.startTimestamp; return stakerData[_address].lastClaimTimestamp > getTimestamp() ? 0 : getTimestamp() - stakerData[_address].lastClaimTimestamp; } /** * @dev Returns the total staking multiplier of `_address`. */ function getStakingMultiplier(address _address) public view returns (uint256) { return 100 + getInhibitorMultiplier(_address) + getLockedMultiplier(_address) + getLordMultiplier(_address); } /** * @dev Returns the Inhibitor staking multiplier of `_address`. */ function getInhibitorMultiplier(address _address) public view returns (uint256) { uint256 inhibBonus = INHIB.balanceOf(_address) * inhibitorBonus; return inhibBonus > 100 ? 100 : inhibBonus; } /** * @dev Returns the optional lock staking multiplier of `_address`. */ function getLockedMultiplier(address _address) public view returns (uint256) { return stakerData[_address].stakedUnlockTimestamp > 0 ? lockedBonus : 0; } /** * @dev Returns the Lord staking multiplier of `_address`. */ function getLordMultiplier(address _address) public view returns (uint256) { if (address(LORD) == address(0)) return 0; return LORD.balanceOf(_address) > 0 ? lordBonus : 0; } /** * @dev Returns the current `_stakingContract` unit balance of `_address`. */ function getUserUnitBalance(address _address, address _stakingContract) public view returns (uint256) { return stakeableUnits[_stakeableUnitsLocations[_stakingContract]].stakeableContract.balanceOf(_address); } /** * @dev Returns whether `_address` is staked overall or not. */ function getUserIsStaked(address _address) public view returns (bool) { uint256 units = totalStakeableUnits; if (units == 0) return false; for (uint256 i = 1; i <= units; i++){ if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){ return true; } } return false; } /** * @dev Returns whether `_address` has `_stakingContract` units staked or not. */ function getUserStakingStatus(address _address, address _stakingContract) public view returns (bool) { return stakeableUnits[_stakeableUnitsLocations[_stakingContract]].stakeableContract.getStakingStatus(_address); } /** * @dev Returns the daily token yield of `_address`. * - Note: This is returned in wei which is the tiniest unit so to see the daily yield in whole tokens divide by 1000000000000000000. */ function getUserDailyYield(address _address) public view returns (uint256) { uint256 units = totalStakeableUnits; if (units == 0) return 0; uint256 rewards; for (uint256 i = 1; i <= units; i++){ if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){ rewards += stakeableUnits[i].stakeableContract.balanceOf(_address) * stakeableUnits[i].dailyYield; } } return rewards * getStakingMultiplier(_address) / 100; } /** * @dev Updates the yield of `_stakingContract`, only the smart contract owner can call this. */ function updateUnitYield(address _stakingContract, uint256 _newYield) public onlyOwner { uint256 location = _stakeableUnitsLocations[_stakingContract]; require(location != 0, "UnknownStakeableUnit"); stakeableUnits[location].dailyYield = _newYield * etherConversion; stakeableUnits[location].baseYield = stakeableUnits[location].dailyYield / 86400; } /** * @dev Returns whether `_address` will lock in rewards on receiving a new staked token. Must have been > 1 hour since last claim. */ function needsRewardsUpdate(address _address) public view returns (bool) { return 3600 < getTimeSinceClaimed(_address); } /** * @dev Adds `_unitAddress` as a stakeable unit, only the smart contract owner can call this. */ function addApprovedUnit(address _unitAddress) public onlyOwner { _approvedUnits[_unitAddress] = true; } /** * @dev Removes `_unitAddress` as a stakeable unit, only the smart contract owner can call this. */ function removeApprovedUnit(address _unitAddress) public onlyOwner { delete _approvedUnits[_unitAddress]; } /** * @dev Start staking for an approved unit with the daily yield of `_dailyYield`, only approved units can call this. */ function startSeason(uint256 _dailyYield) public onlyApprovedUnit { uint256 newUnit = ++totalStakeableUnits; _stakeableUnitsLocations[_msgSender()] = newUnit; stakeableUnits[newUnit].stakeableContract = IUnit(_msgSender()); stakeableUnits[newUnit].dailyYield = _dailyYield * etherConversion; stakeableUnits[newUnit].baseYield = stakeableUnits[newUnit].dailyYield / 86400; if (!seasonData.active){ seasonData.active = true; seasonData.startTimestamp = block.timestamp; } } /** * @dev Ends staking for all approved units, only approved units can call this. */ function endSeason() public onlyApprovedUnit { seasonData.endTimestamp = block.timestamp; delete seasonData.active; } /** * @dev Updates the Inhibitor smart contract address to `_address`, only the smart contract owner can call this. */ function setInhibitor(address _address) public onlyOwner { INHIB = genericBalanceOf(_address); } /** * @dev Updates the Lord smart contract address to `_address`, only the smart contract owner can call this. */ function setLord(address _address) public onlyOwner { LORD = genericBalanceOf(_address); } /** * @dev Returns the current smart contract owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns information about the current Staking Season. * - In the format: Whether Staking is active or not, what time staking started, what time staking ended (0 = has not ended). */ function getSeasonData() public view returns (_seasonData memory) { return seasonData; } /** * @dev Returns information about `_address` approved unit. * - In the format: Contract Address, Tokens generated per day, tokens generated per second. * - If zeros are returns, `_address` is not an approved unit. */ function getUnitDataByAddress(address _address) public view returns (_stakeableUnit memory) { return stakeableUnits[_stakeableUnitsLocations[_address]]; } /** * @dev Returns information about the number `_location` approved unit. * - In the format: Contract Address, Tokens generated per day, tokens generated per second. * - If zeros are returns, that unit location does not exist. */ function getUnitDataByLocation(uint256 _location) public view returns (_stakeableUnit memory) { return stakeableUnits[_location]; } /** * @dev Returns information about `_address`'s staking data. * - In the format: Total Accumulated rewards in Wei, Timestamp since last token claim, timestamp tokens are unstakeable (0 = unlocked). * - If zeros are returns, `_address` has no data. */ function getAddressData(address _address) public view returns (_stakerData memory) { return stakerData[_address]; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner == address(0)) revert NewOwnerZeroAddress(); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Returns the daily token yield of `_address`. - Note: This is returned in wei which is the tiniest unit so to see the daily yield in whole tokens divide by 1000000000000000000./
function getUserDailyYield(address _address) public view returns (uint256) { uint256 units = totalStakeableUnits; if (units == 0) return 0; uint256 rewards; for (uint256 i = 1; i <= units; i++){ if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){ rewards += stakeableUnits[i].stakeableContract.balanceOf(_address) * stakeableUnits[i].dailyYield; } } return rewards * getStakingMultiplier(_address) / 100; }
14,326,274
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); balances[_sender] = balances[_sender].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowances[_owner][_spender] = _amount; emit APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
function ONMINT315(address _target, uint256 _amount) internal {
2,554,172
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ /** * @title PA1D (CXIP) * @author CXIP-Labs * @notice A smart contract for providing royalty info, collecting royalties, and distributing it to configured payout wallets. * @dev This smart contract is not intended to be used directly. Apply it to any of your ERC721 or ERC1155 smart contracts through a delegatecall fallback. */ contract PA1D { /** * @notice Event emitted when setting/updating royalty info/fees. This is used by Rarible V1. * @dev Emits event in order to comply with Rarible V1 royalty spec. * @param tokenId Specific token id for which royalty info is being set, set as 0 for all tokens inside of the smart contract. * @param recipients Address array of wallets that will receive tha royalties. * @param bps Uint256 array of base points(percentages) that each wallet(specified in recipients) will receive from the royalty payouts. Make sure that all the base points add up to a total of 10000. */ event SecondarySaleFees(uint256 tokenId, address[] recipients, uint256[] bps); /** * @dev Use this modifier to lock public functions that should not be accesible to non-owners. */ modifier onlyOwner() { require(isOwner(), "PA1D: caller not an owner"); _; } /** * @notice Constructor is empty and not utilised. * @dev Since the smart contract is being used inside of a fallback context, the constructor function is not being used. */ constructor() {} /** * @notice Initialise the smart contract on source smart contract deployment/initialisation. * @dev Use the init function once, when deploying or initialising your overlying smart contract. * @dev Take great care to not expose this function to your other public functions. * @param tokenId Specify a particular token id only if using the init function for a special case. Otherwise leave empty(0). * @param receiver The address for the default receiver of all royalty payouts. Recommended to use the overlying smart contract address. This will allow the PA1D smart contract to handle all royalty settings, receipt, and distribution. * @param bp The default base points(percentage) for royalty payouts. */ function init( uint256 tokenId, address payable receiver, uint256 bp ) public onlyOwner {} /** * @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices. * @return The address of the top-level CXIP Registry smart contract. */ function getRegistry() internal pure returns (ICxipRegistry) { return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade); } /** * @notice Check if the underlying identity has sender as registered wallet. * @dev Check the overlying smart contract's identity for wallet registration. * @param sender Address which should be checked against the identity. * @return Returns true if the sender is a valid wallet of the identity. */ function isIdentityWallet(address sender) internal view returns (bool) { return isIdentityWallet(ICxipERC(address(this)).getIdentity(), sender); } /** * @notice Check if a specific identity has sender as registered wallet. * @dev Don't use this function directly unless you know what you're doing. * @param identity Address of the identity smart contract. * @param sender Address which should be checked against the identity. * @return Returns true if the sender is a valid wallet of the identity. */ function isIdentityWallet(address identity, address sender) internal view returns (bool) { if (Address.isZero(identity)) { return false; } return ICxipIdentity(identity).isWalletRegistered(sender); } /** * @notice Check if message sender is a legitimate owner of the smart contract * @dev We check owner, admin, and identity for a more comprehensive coverage. * @return Returns true is message sender is an owner. */ function isOwner() internal view returns (bool) { ICxipERC erc = ICxipERC(address(this)); return (msg.sender == erc.owner() || msg.sender == erc.admin() || isIdentityWallet(erc.getIdentity(), msg.sender)); } /** * @dev Gets the default royalty payment receiver address from storage slot. * @return receiver Wallet or smart contract that will receive the initial royalty payouts. */ function _getDefaultReceiver() internal view returns (address payable receiver) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultReceiver')) - 1); assembly { receiver := sload( /* slot */ 0xaee4e97c19ce50ea5345ba9751676d533a3a7b99c3568901208f92f9eea6a7f2 ) } } /** * @dev Sets the default royalty payment receiver address to storage slot. * @param receiver Wallet or smart contract that will receive the initial royalty payouts. */ function _setDefaultReceiver(address receiver) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultReceiver')) - 1); assembly { sstore( /* slot */ 0xaee4e97c19ce50ea5345ba9751676d533a3a7b99c3568901208f92f9eea6a7f2, receiver ) } } /** * @dev Gets the default royalty base points(percentage) from storage slot. * @return bp Royalty base points(percentage) for royalty payouts. */ function _getDefaultBp() internal view returns (uint256 bp) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultBp')) - 1); assembly { bp := sload( /* slot */ 0xfd198c3b406b2320ea9f4a413c7a69a7592dbfc4175b8c252fec24223e68b720 ) } } /** * @dev Sets the default royalty base points(percentage) to storage slot. * @param bp Uint256 of royalty percentage, provided in base points format. */ function _setDefaultBp(uint256 bp) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultBp')) - 1); assembly { sstore( /* slot */ 0xfd198c3b406b2320ea9f4a413c7a69a7592dbfc4175b8c252fec24223e68b720, bp ) } } /** * @dev Gets the royalty payment receiver address, for a particular token id, from storage slot. * @return receiver Wallet or smart contract that will receive the royalty payouts for a particular token id. */ function _getReceiver(uint256 tokenId) internal view returns (address payable receiver) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.receiver", tokenId))) - 1 ); assembly { receiver := sload(slot) } } /** * @dev Sets the royalty payment receiver address, for a particular token id, to storage slot. * @param tokenId Uint256 of the token id to set the receiver for. * @param receiver Wallet or smart contract that will receive the royalty payouts for a particular token id. */ function _setReceiver(uint256 tokenId, address receiver) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.receiver", tokenId))) - 1 ); assembly { sstore(slot, receiver) } } /** * @dev Gets the royalty base points(percentage), for a particular token id, from storage slot. * @return bp Royalty base points(percentage) for the royalty payouts of a specific token id. */ function _getBp(uint256 tokenId) internal view returns (uint256 bp) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { bp := sload(slot) } } /** * @dev Sets the royalty base points(percentage), for a particular token id, to storage slot. * @param tokenId Uint256 of the token id to set the base points for. * @param bp Uint256 of royalty percentage, provided in base points format, for a particular token id. */ function _setBp(uint256 tokenId, uint256 bp) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { sstore(slot, bp) } } function _getPayoutAddresses() internal view returns (address payable[] memory addresses) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.addresses')) - 1); bytes32 slot = 0xda9d0b1bc91e594968e30b896be60318d483303fc3ba08af8ac989d483bdd7ca; uint256 length; assembly { length := sload(slot) } addresses = new address payable[](length); address payable value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); assembly { value := sload(slot) } addresses[i] = value; } } function _setPayoutAddresses(address payable[] memory addresses) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.addresses')) - 1); bytes32 slot = 0xda9d0b1bc91e594968e30b896be60318d483303fc3ba08af8ac989d483bdd7ca; uint256 length = addresses.length; assembly { sstore(slot, length) } address payable value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); value = addresses[i]; assembly { sstore(slot, value) } } } function _getPayoutBps() internal view returns (uint256[] memory bps) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.bps')) - 1); bytes32 slot = 0x7862b872ab9e3483d8176282b22f4ac86ad99c9035b3f794a541d84a66004fa2; uint256 length; assembly { length := sload(slot) } bps = new uint256[](length); uint256 value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); assembly { value := sload(slot) } bps[i] = value; } } function _setPayoutBps(uint256[] memory bps) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.bps')) - 1); bytes32 slot = 0x7862b872ab9e3483d8176282b22f4ac86ad99c9035b3f794a541d84a66004fa2; uint256 length = bps.length; assembly { sstore(slot, length) } uint256 value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); value = bps[i]; assembly { sstore(slot, value) } } } function _getTokenAddress(string memory tokenName) internal view returns (address tokenAddress) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.tokenAddress", tokenName))) - 1 ); assembly { tokenAddress := sload(slot) } } function _setTokenAddress(string memory tokenName, address tokenAddress) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.tokenAddress", tokenName))) - 1 ); assembly { sstore(slot, tokenAddress) } } /** * @dev Internal function that transfers ETH to all payout recipients. */ function _payoutEth() internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; // accommodating the 2300 gas stipend // adding 1x for each item in array to accomodate rounding errors uint256 gasCost = (23300 * length) + length; uint256 balance = address(this).balance; require(balance - gasCost > 10000, "PA1D: Not enough ETH to transfer"); balance = balance - gasCost; uint256 sending; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); addresses[i].transfer(sending); } } /** * @dev Internal function that transfers tokens to all payout recipients. * @param tokenAddress Smart contract address of ERC20 token. */ function _payoutToken(address tokenAddress) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; IERC20 erc20 = IERC20(tokenAddress); uint256 balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); uint256 sending; //uint256 sent; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } } /** * @dev Internal function that transfers multiple tokens to all payout recipients. * @dev Try to use _payoutToken and handle each token individually. * @param tokenAddresses Array of smart contract addresses of ERC20 tokens. */ function _payoutTokens(address[] memory tokenAddresses) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); IERC20 erc20; uint256 balance; uint256 sending; for (uint256 t = 0; t < tokenAddresses.length; t++) { erc20 = IERC20(tokenAddresses[t]); balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); for (uint256 i = 0; i < addresses.length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } } } /** * @dev This function validates that the call is being made by an authorised wallet. * @dev Will revert entire tranaction if it fails. */ function _validatePayoutRequestor() internal view { if (!isOwner()) { bool matched; address payable[] memory addresses = _getPayoutAddresses(); address payable sender = payable(msg.sender); for (uint256 i = 0; i < addresses.length; i++) { if (addresses[i] == sender) { matched = true; break; } } require(matched, "PA1D: sender not authorized"); } } /** * @notice Set the wallets and percentages for royalty payouts. * @dev Function can only we called by owner, admin, or identity wallet. * @dev Addresses and bps arrays must be equal length. Bps values added together must equal 10000 exactly. * @param addresses An array of all the addresses that will be receiving royalty payouts. * @param bps An array of the percentages that each address will receive from the royalty payouts. */ function configurePayouts(address payable[] memory addresses, uint256[] memory bps) public onlyOwner { require(addresses.length == bps.length, "PA1D: missmatched array lenghts"); uint256 totalBp; for (uint256 i = 0; i < addresses.length; i++) { totalBp = totalBp + bps[i]; } require(totalBp == 10000, "PA1D: bps down't equal 10000"); _setPayoutAddresses(addresses); _setPayoutBps(bps); } /** * @notice Show the wallets and percentages of payout recipients. * @dev These are the recipients that will be getting royalty payouts. * @return addresses An array of all the addresses that will be receiving royalty payouts. * @return bps An array of the percentages that each address will receive from the royalty payouts. */ function getPayoutInfo() public view returns (address payable[] memory addresses, uint256[] memory bps) { addresses = _getPayoutAddresses(); bps = _getPayoutBps(); } /** * @notice Get payout of all ETH in smart contract. * @dev Distribute all the ETH(minus gas fees) to payout recipients. */ function getEthPayout() public { _validatePayoutRequestor(); _payoutEth(); } /** * @notice Get payout for a specific token address. Token must have a positive balance! * @dev Contract owner, admin, identity wallet, and payout recipients can call this function. * @param tokenAddress An address of the token for which to issue payouts for. */ function getTokenPayout(address tokenAddress) public { _validatePayoutRequestor(); _payoutToken(tokenAddress); } /** * @notice Get payout for a specific token name. Token must have a positive balance! * @dev Contract owner, admin, identity wallet, and payout recipients can call this function. * @dev Avoid using this function at all costs, due to high gas usage, and no guarantee for token support. * @param tokenName A string of the token name for which to issue payouts for. */ function getTokenPayoutByName(string memory tokenName) public { _validatePayoutRequestor(); address tokenAddress = PA1D(payable(getRegistry().getPA1D())).getTokenAddress(tokenName); require(!Address.isZero(tokenAddress), "PA1D: Token address not found"); _payoutToken(tokenAddress); } /** * @notice Get payouts for tokens listed by address. Tokens must have a positive balance! * @dev Each token balance must be equal or greater than 10000. Otherwise calculating BP is difficult. * @param tokenAddresses An address array of tokens to issue payouts for. */ function getTokensPayout(address[] memory tokenAddresses) public { _validatePayoutRequestor(); _payoutTokens(tokenAddresses); } /** * @notice Get payouts for tokens listed by name. Tokens must have a positive balance! * @dev Each token balance must be equal or greater than 10000. Otherwise calculating BP is difficult. * @dev Avoid using this function at all costs, due to high gas usage, and no guarantee for token support. * @param tokenNames A string array of token names to issue payouts for. */ function getTokensPayoutByName(string[] memory tokenNames) public { _validatePayoutRequestor(); uint256 length = tokenNames.length; address[] memory tokenAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { address tokenAddress = PA1D(payable(getRegistry().getPA1D())).getTokenAddress( tokenNames[i] ); require(!Address.isZero(tokenAddress), "PA1D: Token address not found"); tokenAddresses[i] = tokenAddress; } _payoutTokens(tokenAddresses); } /** * @notice Inform about supported interfaces(eip-165). * @dev Provides the supported interface ids that this contract implements. * @param interfaceId Bytes4 of the interface, derived through bytes4(keccak256('sampleFunction(uin256,address)')). * @return True if function is supported/implemented, false if not. */ function supportsInterface(bytes4 interfaceId) public pure returns (bool) { if ( // EIP2981 // bytes4(keccak256('royaltyInfo(uint256,uint256)')) == 0x2a55205a interfaceId == 0x2a55205a || // Rarible V1 // bytes4(keccak256('getFeeBps(uint256)')) == 0xb7799584 interfaceId == 0xb7799584 || // Rarible V1 // bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb interfaceId == 0xb9c4d9fb || // Manifold // bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 interfaceId == 0xbb3bafd6 || // Foundation // bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c interfaceId == 0xd5a06d4c || // SuperRare // bytes4(keccak256('tokenCreator(address,uint256)')) == 0xb85ed7e4 interfaceId == 0xb85ed7e4 || // SuperRare // bytes4(keccak256('calculateRoyaltyFee(address,uint256,uint256)')) == 0x860110f5 interfaceId == 0x860110f5 || // Zora // bytes4(keccak256('marketContract()')) == 0xa1794bcd interfaceId == 0xa1794bcd || // Zora // bytes4(keccak256('tokenCreators(uint256)')) == 0xe0fd045f interfaceId == 0xe0fd045f || // Zora // bytes4(keccak256('bidSharesForToken(uint256)')) == 0xf9ce0582 interfaceId == 0xf9ce0582 ) { return true; } return false; } /** * @notice Set the royalty information for entire contract, or a specific token. * @dev Take great care to not make this function accessible by other public functions in your overlying smart contract. * @param tokenId Set a specific token id, or leave at 0 to set as default parameters. * @param receiver Wallet or smart contract that will receive the royalty payouts. * @param bp Uint256 of royalty percentage, provided in base points format. */ function setRoyalties( uint256 tokenId, address payable receiver, uint256 bp ) public onlyOwner { if (tokenId == 0) { _setDefaultReceiver(receiver); _setDefaultBp(bp); } else { _setReceiver(tokenId, receiver); _setBp(tokenId, bp); } address[] memory receivers = new address[](1); receivers[0] = address(receiver); uint256[] memory bps = new uint256[](1); bps[0] = bp; emit SecondarySaleFees(tokenId, receivers, bps); } // IEIP2981 function royaltyInfo(uint256 tokenId, uint256 value) public view returns (address, uint256) { if (_getReceiver(tokenId) == address(0)) { return (_getDefaultReceiver(), (_getDefaultBp() * value) / 10000); } else { return (_getReceiver(tokenId), (_getBp(tokenId) * value) / 10000); } } // Rarible V1 function getFeeBps(uint256 tokenId) public view returns (uint256[] memory) { uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { bps[0] = _getDefaultBp(); } else { bps[0] = _getBp(tokenId); } return bps; } // Rarible V1 function getFeeRecipients(uint256 tokenId) public view returns (address payable[] memory) { address payable[] memory receivers = new address payable[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); } else { receivers[0] = _getReceiver(tokenId); } return receivers; } // Manifold function getRoyalties(uint256 tokenId) public view returns (address payable[] memory, uint256[] memory) { address payable[] memory receivers = new address payable[](1); uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); bps[0] = _getDefaultBp(); } else { receivers[0] = _getReceiver(tokenId); bps[0] = _getBp(tokenId); } return (receivers, bps); } // Foundation function getFees(uint256 tokenId) public view returns (address payable[] memory, uint256[] memory) { address payable[] memory receivers = new address payable[](1); uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); bps[0] = _getDefaultBp(); } else { receivers[0] = _getReceiver(tokenId); bps[0] = _getBp(tokenId); } return (receivers, bps); } // SuperRare // Hint taken from Manifold's RoyaltyEngine(https://github.com/manifoldxyz/royalty-registry-solidity/blob/main/contracts/RoyaltyEngineV1.sol) // To be quite honest, SuperRare is a closed marketplace. They're working on opening it up but looks like they want to use private smart contracts. // We'll just leave this here for just in case they open the flood gates. function tokenCreator( address, /* contractAddress*/ uint256 tokenId ) public view returns (address) { address receiver = _getReceiver(tokenId); if (receiver == address(0)) { return _getDefaultReceiver(); } return receiver; } // SuperRare function calculateRoyaltyFee( address, /* contractAddress */ uint256 tokenId, uint256 amount ) public view returns (uint256) { if (_getReceiver(tokenId) == address(0)) { return (_getDefaultBp() * amount) / 10000; } else { return (_getBp(tokenId) * amount) / 10000; } } // Zora // we indicate that this contract operates market functions function marketContract() public view returns (address) { return address(this); } // Zora // we indicate that the receiver is the creator, to convince the smart contract to pay function tokenCreators(uint256 tokenId) public view returns (address) { address receiver = _getReceiver(tokenId); if (receiver == address(0)) { return _getDefaultReceiver(); } return receiver; } // Zora // we provide the percentage that needs to be paid out from the sale function bidSharesForToken(uint256 tokenId) public view returns (Zora.BidShares memory bidShares) { // this information is outside of the scope of our bidShares.prevOwner.value = 0; bidShares.owner.value = 0; if (_getReceiver(tokenId) == address(0)) { bidShares.creator.value = _getDefaultBp(); } else { bidShares.creator.value = _getBp(tokenId); } return bidShares; } /** * @notice Get the storage slot for given string * @dev Convert a string to a bytes32 storage slot * @param slot The string name of storage slot(without the 'eip1967.PA1D.' prefix) * @return A bytes32 reference to the storage slot */ function getStorageSlot(string calldata slot) public pure returns (bytes32) { return bytes32(uint256(keccak256(abi.encodePacked("eip1967.PA1D.", slot))) - 1); } /** * @notice Get the smart contract address of a token by common name. * @dev Used only to identify really major/common tokens. Avoid using due to gas usages. * @param tokenName The ticker symbol of the token. For example "USDC" or "DAI". * @return The smart contract address of the token ticker symbol. Or zero address if not found. */ function getTokenAddress(string memory tokenName) public view returns (address) { return _getTokenAddress(tokenName); } /** * @notice Forwards unknown function call to the CXIP hotfixes smart contract(if present) * @dev All unrecognized functions are delegated to hotfixes smart contract which can be utilized to deploy on-chain hotfixes */ function _defaultFallback() internal { /** * @dev Very important to note the use of sha256 instead of keccak256 in this function. Since the registry is made to be front-facing and user friendly, the choice to use sha256 was made due to the accessibility of that function in comparison to keccak. */ address _target = getRegistry().getCustomSource( sha256(abi.encodePacked("eip1967.CXIP.hotfixes")) ); /** * @dev To minimize gas usage, pre-calculate the 32 byte hash and provide the final hex string instead of running the sha256 function on each call inside the smart contract */ // address _target = getRegistry().getCustomSource(0x45f5c3bc3dbabbfab15d44af18b96716cf5bec748c58d54d61c4e7293de6763e); /** * @dev Assembly is used to minimize gas usage and pass the data directly through */ assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Forwarding all unknown functions to default fallback */ fallback() external { _defaultFallback(); } /** * @dev This is intentionally left empty, to make sure that ETH transfers succeed. */ receive() external payable {} } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function isZero(address account) internal pure returns (bool) { return (account == address(0)); } } library Zora { struct Decimal { uint256 value; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal prevOwner; // % of sale value that goes to the original creator of the nft Decimal creator; // % of sale value that goes to the seller (current owner) of the nft Decimal owner; } } // This is a 256 value limit (uint8) enum UriType { ARWEAVE, // 0 IPFS, // 1 HTTP // 2 } // This is a 256 value limit (uint8) enum InterfaceType { NULL, // 0 ERC20, // 1 ERC721, // 2 ERC1155 // 3 } struct Verification { bytes32 r; bytes32 s; uint8 v; } struct CollectionData { bytes32 name; bytes32 name2; bytes32 symbol; address royalties; uint96 bps; } struct Token { address collection; uint256 tokenId; InterfaceType tokenType; address creator; } struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } interface ICxipERC { function admin() external view returns (address); function getIdentity() external view returns (address); function isAdmin() external view returns (bool); function isOwner() external view returns (bool); function name() external view returns (string memory); function owner() external view returns (address); function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); } interface ICxipIdentity { function addSignedWallet( address newWallet, uint8 v, bytes32 r, bytes32 s ) external; function addWallet(address newWallet) external; function connectWallet() external; function createERC721Token( address collection, uint256 id, TokenData calldata tokenData, Verification calldata verification ) external returns (uint256); function createERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData ) external returns (address); function createCustomERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData, bytes32 slot, bytes memory bytecode ) external returns (address); function init(address wallet, address secondaryWallet) external; function getAuthorizer(address wallet) external view returns (address); function getCollectionById(uint256 index) external view returns (address); function getCollectionType(address collection) external view returns (InterfaceType); function getWallets() external view returns (address[] memory); function isCollectionCertified(address collection) external view returns (bool); function isCollectionRegistered(address collection) external view returns (bool); function isNew() external view returns (bool); function isOwner() external view returns (bool); function isTokenCertified(address collection, uint256 tokenId) external view returns (bool); function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool); function isWalletRegistered(address wallet) external view returns (bool); function listCollections(uint256 offset, uint256 length) external view returns (address[] memory); function nextNonce(address wallet) external view returns (uint256); function totalCollections() external view returns (uint256); function isCollectionOpen(address collection) external pure returns (bool); } interface ICxipRegistry { function getAsset() external view returns (address); function getAssetSigner() external view returns (address); function getAssetSource() external view returns (address); function getCopyright() external view returns (address); function getCopyrightSource() external view returns (address); function getCustomSource(bytes32 name) external view returns (address); function getCustomSourceFromString(string memory name) external view returns (address); function getERC1155CollectionSource() external view returns (address); function getERC721CollectionSource() external view returns (address); function getIdentitySource() external view returns (address); function getPA1D() external view returns (address); function getPA1DSource() external view returns (address); function getProvenance() external view returns (address); function getProvenanceSource() external view returns (address); function owner() external view returns (address); function setAsset(address proxy) external; function setAssetSigner(address source) external; function setAssetSource(address source) external; function setCopyright(address proxy) external; function setCopyrightSource(address source) external; function setCustomSource(string memory name, address source) external; function setERC1155CollectionSource(address source) external; function setERC721CollectionSource(address source) external; function setIdentitySource(address source) external; function setPA1D(address proxy) external; function setPA1DSource(address source) external; function setProvenance(address proxy) external; function setProvenanceSource(address source) external; } interface IERC20 { function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); }
Sets the royalty base points(percentage), for a particular token id, to storage slot. tokenId Uint256 of the token id to set the base points for. bp Uint256 of royalty percentage, provided in base points format, for a particular token id./
function _setBp(uint256 tokenId, uint256 bp) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { sstore(slot, bp) } }
5,789,099
./full_match/137/0x15B8C75c024acba8c114C21F42eb515A762c0014/sources/src/BobVault.sol
Invests excess tokens into the yield provider. Callable only by the contract owner / proxy admin / invest admin. _token address of collateral to invest./
function invest(address _token) external { require(msg.sender == investAdmin || _isOwner(), "BobVault: not authorized"); Collateral storage token = collateral[_token]; require(token.price > 0, "BobVault: unsupported collateral"); _investExcess(_token, token.yield, token.buffer); }
3,757,713
pragma solidity ^0.4.13; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC827 is ERC20 { function approveAndCall( address _spender, uint256 _value, bytes _data) public payable returns (bool); function transferAndCall( address _to, uint256 _value, bytes _data) public payable returns (bool); function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } contract Certifier { event Confirmed(address indexed who); event Revoked(address indexed who); function certified(address) public constant returns (bool); function get(address, string) public constant returns (bytes32); function getAddress(address, string) public constant returns (address); function getUint(address, string) public constant returns (uint); } contract Certifiable is Ownable { Certifier public certifier; event CertifierChanged(address indexed newCertifier); constructor(address _certifier) public { certifier = Certifier(_certifier); } function updateCertifier(address _address) public onlyOwner returns (bool success) { require(_address != address(0)); emit CertifierChanged(_address); certifier = Certifier(_address); return true; } } contract KYCToken is Certifiable { mapping(address => bool) public kycPending; mapping(address => bool) public managers; event ManagerAdded(address indexed newManager); event ManagerRemoved(address indexed removedManager); modifier onlyManager() { require(managers[msg.sender] == true); _; } modifier isKnownCustomer(address _address) { require(!kycPending[_address] || certifier.certified(_address)); if (kycPending[_address]) { kycPending[_address] = false; } _; } constructor(address _certifier) public Certifiable(_certifier) { } function addManager(address _address) external onlyOwner { managers[_address] = true; emit ManagerAdded(_address); } function removeManager(address _address) external onlyOwner { managers[_address] = false; emit ManagerRemoved(_address); } } contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; address public tokenWallet; /** * @dev Constructor, takes token wallet address. * @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale */ function AllowanceCrowdsale(address _tokenWallet) public { require(_tokenWallet != address(0)); tokenWallet = _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return token.allowance(tokenWallet, this); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transferFrom(tokenWallet, _beneficiary, _tokenAmount); } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract ERC827Token is ERC827, StandardToken { /** * @dev Addition to ERC20 token methods. It allows to * @dev approve the transfer of value and execute a call with the sent data. * * @dev Beware that changing an allowance with this method brings the risk that * @dev someone may use both the old and the new allowance by unfortunate * @dev transaction ordering. One possible solution to mitigate this race condition * @dev is to first reduce the spender's allowance to 0 and set the desired value * @dev afterwards: * @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @param _spender The address that will spend the funds. * @param _value The amount of tokens to be spent. * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function approveAndCall(address _spender, uint256 _value, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * @dev address and execute a call with the sent data on the same transaction * * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferAndCall(address _to, uint256 _value, bytes _data) public payable returns (bool) { require(_to != address(this)); super.transfer(_to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens from one address to * @dev another and make a contract call on the same transaction * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transferred * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To increment * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApprovalAndCall(address _spender, uint _addedValue, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To decrement * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApprovalAndCall(address _spender, uint _subtractedValue, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract EDUCrowdsale is AllowanceCrowdsale, CappedCrowdsale, TimedCrowdsale, Ownable, Certifiable { using SafeMath for uint256; uint256 constant FIFTY_ETH = 50 * (10 ** 18); uint256 constant HUNDRED_AND_FIFTY_ETH = 150 * (10 ** 18); uint256 constant TWO_HUNDRED_AND_FIFTY_ETH = 250 * (10 ** 18); EDUToken public token; event TokenWalletChanged(address indexed newTokenWallet); event WalletChanged(address indexed newWallet); constructor( address _wallet, EDUToken _token, address _tokenWallet, uint256 _cap, uint256 _openingTime, uint256 _closingTime, address _certifier ) public Crowdsale(getCurrentRate(), _wallet, _token) AllowanceCrowdsale(_tokenWallet) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) Certifiable(_certifier) { token = _token; } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { if (certifier.certified(_beneficiary)) { token.transferFrom(tokenWallet, _beneficiary, _tokenAmount); } else { token.delayedTransferFrom(tokenWallet, _beneficiary, _tokenAmount); } } /** * @dev Returns the rate of tokens per wei at the present time. * Note that, as price _increases_ with time, the rate _decreases_. * @return The number of tokens a buyer gets per wei at a given time */ function getCurrentRate() public view returns (uint256) { if (block.timestamp < 1528156799) { // 4th of June 2018 23:59:59 GTC return 1050; } else if (block.timestamp < 1528718400) { // 11th of June 2018 12:00:00 GTC return 940; } else if (block.timestamp < 1529323200) { // 18th of June 2018 12:00:00 GTC return 865; } else if (block.timestamp < 1529928000) { // 25th of June 2018 12:00:00 GTC return 790; } else { return 750; } } /** * @dev Overrides parent method taking into account variable rate. * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); uint256 volumeBonus = _getVolumeBonus(currentRate, _weiAmount); return currentRate.mul(_weiAmount).add(volumeBonus); } function _getVolumeBonus(uint256 _currentRate, uint256 _weiAmount) internal view returns (uint256) { if (_weiAmount >= FIFTY_ETH) { if (_weiAmount >= HUNDRED_AND_FIFTY_ETH) { if (_weiAmount >= TWO_HUNDRED_AND_FIFTY_ETH) { return _currentRate.mul(_weiAmount).mul(15).div(100); } return _currentRate.mul(_weiAmount).mul(10).div(100); } return _currentRate.mul(_weiAmount).mul(5).div(100); } return 0; } function changeTokenWallet(address _tokenWallet) external onlyOwner { require(_tokenWallet != address(0x0)); tokenWallet = _tokenWallet; emit TokenWalletChanged(_tokenWallet); } function changeWallet(address _wallet) external onlyOwner { require(_wallet != address(0x0)); wallet = _wallet; emit WalletChanged(_wallet); } } contract EDUToken is BurnableToken, KYCToken, ERC827Token { using SafeMath for uint256; string public constant name = "EDU Token"; string public constant symbol = "EDU"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 48000000 * (10 ** uint256(decimals)); constructor(address _certifier) public KYCToken(_certifier) { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function transfer(address _to, uint256 _value) public isKnownCustomer(msg.sender) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public isKnownCustomer(_from) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public isKnownCustomer(_spender) returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public isKnownCustomer(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public isKnownCustomer(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } function delayedTransferFrom(address _tokenWallet, address _to, uint256 _value) public onlyManager returns (bool) { transferFrom(_tokenWallet, _to, _value); kycPending[_to] = true; } }
Addition to StandardToken methods. Increase the amount of tokens that an owner allowed to a spender and execute a call with the sent data. approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol _spender The address which will spend the funds. _addedValue The amount of tokens to increase the allowance by. _data ABI-encoded contract call to call `_spender` address./ solium-disable-next-line security/no-call-value
function increaseApprovalAndCall(address _spender, uint _addedValue, bytes _data) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call.value(msg.value)(_data)); return true; }
924,719
./partial_match/1/0xE8D0A73ED68231F209bdDB1b0AAcc37C38C16E45/sources/BadgerRewardsManager.sol
===== Permissioned Functions: Distributor ===== Atomically add to strategy positions
function transferWant(address want, address strategy, uint256 amount) external { _onlyDistributor(); _onlyApprovedStrategies(strategy); require(IStrategy(strategy).want() == want, "Incorrect want for strategy"); require(IERC20Upgradeable(want).transfer(strategy, amount), "Want transfer failed"); IStrategy(strategy).deposit(); }
16,062,390
./full_match/56/0xCfc68CBFbFe35cE1bde94CB5266ebe75Eb5495D8/sources/FERRADistribution.sol
Set a token contract address/
function setTokenReward(address _address) public onlyOwner { tokenReward = token(_address); }
3,231,871
./full_match/4/0x9450CBEA6810599FF1db16cC3f5BA09659D5f3B8/sources/contracts/YKPartsOfLife.sol
disable gas-less listings in case OS wallet is compromised
function setOpenSeaProxyDisabled(bool _isDisabled) external onlyOwner { isOpenSeaProxyDisabled = _isDisabled; }
12,394,599
pragma solidity >=0.5.16; // SPDX-License-Identifier: MIT import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; /************************************************** */ /* no1s1 App Smart Contract */ /************************************************** */ contract no1s1App { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract No1s1Data no1s1Data; // State variable referencing the data contract uint256 private constant MEDITATION_PRICE = 0.01 ether; // Price per minute meditation in no1s1 uint256 private constant ESCROW_AMOUNT = 0.5 ether; // Escrow amount to be paid to meditate uint256 private constant MAX_DURATION = 60; // Maximum allowed duration to meditate per user in minutes // Minimum values for battery state of charge uint256 private constant FULL_VALUE = 75; uint256 private constant GOOD_VALUE = 45; uint256 private constant LOW_VALUE = 25; // Minimum duration for given battery state of charge uint256 private constant FULL_DURATION = 60; uint256 private constant GOOD_DURATION = 30; uint256 private constant LOW_DURATION = 10; // Mappings (key value pairs) mapping(address => uint256) authorizedBackends; // Mapping to store authorized backends that can call into the app contract /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // Emitted when new backend is de-/authorized event AuthorizedBackend(address backendAddress); event DeAuthorizedBackend(address backendAddress); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ /** * @dev Modifier that requires the "contractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires that the contract calling into the data contract is authorized */ modifier requireBackend() { require(authorizedBackends[msg.sender] == 1, "Backend is not authorized"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * tells the App contract where to find the data of the app contract (address) */ constructor(address dataContract) { contractOwner = msg.sender; no1s1Data = No1s1Data(dataContract); // register msg.sender as first backend authorizeBackend(msg.sender); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev authorize app contract to call into data contract * @return A bool that is the current authorization status */ function authorizeBackend(address backendAddress) public requireContractOwner returns(bool) { authorizedBackends[backendAddress] = 1; emit AuthorizedBackend(backendAddress); return true; } /** * @dev deauthorize app contract to call into data contract * @return A bool that is the current authorization status */ function deAuthorizeBackend(address backendAddress) public requireContractOwner returns(bool) { delete authorizedBackends[backendAddress]; emit DeAuthorizedBackend(backendAddress); return true; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function setAccessabilityStatus(bool mode) external requireContractOwner { no1s1Data.setAccessabilityStatus(mode); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function setOccupationStatus(bool mode) external requireContractOwner { no1s1Data.setOccupationStatus(mode); } /** * @dev function to log data in smart contract when broadcasting from backend to frontend */ function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time) external requireBackend { no1s1Data.broadcastData(_Bcurrent, _Bvoltage, _BSOC, _Pvoltage, _Senergy, _Time, FULL_VALUE, GOOD_VALUE, LOW_VALUE); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function no1s1InfoLog(uint256 _Time) external requireBackend { no1s1Data.no1s1InfoLog(_Time); } /** * @dev buy function to access no1s1, only pass _selectedDuration and _username! */ function buy(uint256 _selectedDuration, string calldata _username) external payable { no1s1Data.buy{value: msg.value}(_selectedDuration, msg.sender, _username, ESCROW_AMOUNT, MAX_DURATION, GOOD_DURATION, LOW_DURATION); } /** * @dev function to check whether QR code is valid and authorizes to unlock door * Pass address of function caller to data contract to enable role modifier */ function checkAccess(bytes32 _key) external requireBackend { no1s1Data.checkAccess(_key, GOOD_DURATION, LOW_DURATION); } /** * @dev function triggered by back-end shortly after access() function with sensor feedback * Pass address of function caller to data contract to enable role modifier */ function checkActivity(bool _pressureDetected, bytes32 _key) external requireBackend { no1s1Data.checkActivity(_pressureDetected, _key); } /** * @dev function triggered by user after leaving no1s1. resets the occupancy state, pays back escrow, and sends out confirmation NFT */ function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external requireBackend { no1s1Data.exit(_doorOpened, _actualDuration, _key); } /** * @dev function triggered by user after leaving no1s1. resets the occupancy state, pays back escrow, and sends out confirmation NFT */ function refundEscrow(string calldata _username) external { no1s1Data.refundEscrow(msg.sender, _username, MEDITATION_PRICE); } // call from data contract function isDataContractOperational() external view returns(bool) { return no1s1Data.isOperational(); } /** * @dev Get operating status of no1s1 (main state variables) */ function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance) { return no1s1Data.howAmI(); } /** * @dev Get address of no1s1 */ function whoAmI() external view returns(address no1s1Address) { return no1s1Data.whoAmI(); } /** * @dev Get balance of no1s1 */ function howRichAmI() external view returns(uint256 no1s1Balance) { return no1s1Data.howRichAmI(); } /** * @dev get latest entries of UsageLog (max 10) */ function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations) { return no1s1Data.getUsageLog(); } /** * @dev retrieve values needed to buy meditation time */ function checkBuyStatus() external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate) { return no1s1Data.checkBuyStatus(MEDITATION_PRICE, FULL_DURATION, GOOD_DURATION, LOW_DURATION); } /** * @dev retrieve the latest technical logs */ function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage) { return no1s1Data.checkLastTechLogs(); } /** * @dev retrieve user information with key (QR code) */ function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return no1s1Data.checkUserKey(_key); } /** * @dev retrieve user information with username */ function checkUserName(string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return no1s1Data.checkUserName(msg.sender, _username); } } /********************************************************************************************/ /* Interface to Data Contract */ /********************************************************************************************/ //visibility (also in data contract) must be `external` and signature of functions must match! interface No1s1Data { function setAccessabilityStatus(bool mode) external; function setOccupationStatus(bool mode) external; function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time, uint256 FULL_VALUE, uint256 GOOD_VALUE, uint256 LOW_VALUE) external; function no1s1InfoLog(uint256 _Time) external; function buy(uint256 _selectedDuration, address txSender, string calldata _username, uint256 ESCROW_AMOUNT, uint256 MAX_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external payable; function checkAccess(bytes32 _key, uint256 GOOD_DURATION, uint256 LOW_DURATION) external; function checkActivity(bool _pressureDetected, bytes32 _key) external; function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external; function refundEscrow(address _sender, string calldata _username, uint256 MEDITATION_PRICE) external; function isOperational() external view returns(bool); function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance); function whoAmI() external view returns(address no1s1Address); function howRichAmI() external view returns(uint256 no1s1Balance); function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations); function checkBuyStatus(uint256 MEDITATION_PRICE, uint256 FULL_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate); function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage); function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow); function checkUserName(address, string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow); }
authorize app contract to call into data contract return A bool that is the current authorization status/
function authorizeBackend(address backendAddress) public requireContractOwner returns(bool) { authorizedBackends[backendAddress] = 1; emit AuthorizedBackend(backendAddress); return true; }
12,788,225
pragma solidity >=0.4.0 <0.6.0; /* Copyright 2017, Jordi Baylina, RJ Ewing Contributors: Adrià Massanet <[email protected]>, Griff Green, Arthur Lunn This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "@aragon/os/contracts/apps/AragonApp.sol"; import "./LiquidPledgingStorage.sol"; contract Pledges is AragonApp, LiquidPledgingStorage { // Limits inserted to prevent large loops that could prevent canceling uint constant MAX_DELEGATES = 10; // a constant for when a delegate is requested that is not in the system uint64 constant NOTFOUND = 0xFFFFFFFFFFFFFFFF; ///////////////////////////// // Public constant functions //////////////////////////// /// @notice A constant getter that returns the total number of pledges /// @return The total number of Pledges in the system function numberOfPledges() external view returns (uint) { return pledges.length - 1; } /// @notice A getter that returns the details of the specified pledge /// @param idPledge the id number of the pledge being queried /// @return the amount, owner, the number of delegates (but not the actual /// delegates, the intendedProject (if any), the current commit time and /// the previous pledge this pledge was derived from function getPledge(uint64 idPledge) external view returns( uint amount, uint64 owner, uint64 nDelegates, uint64 intendedProject, uint64 commitTime, uint64 oldPledge, address token, PledgeState pledgeState ) { Pledge memory p = _findPledge(idPledge); amount = p.amount; owner = p.owner; nDelegates = uint64(p.delegationChain.length); intendedProject = p.intendedProject; commitTime = p.commitTime; oldPledge = p.oldPledge; token = p.token; pledgeState = p.pledgeState; } //////////////////// // Internal methods //////////////////// /// @notice This creates a Pledge with an initial amount of 0 if one is not /// created already; otherwise it finds the pledge with the specified /// attributes; all pledges technically exist, if the pledge hasn't been /// created in this system yet it simply isn't in the hash array /// hPledge2idx[] yet /// @param owner The owner of the pledge being looked up /// @param delegationChain The list of delegates in order of authority /// @param intendedProject The project this pledge will Fund after the /// commitTime has passed /// @param commitTime The length of time in seconds the Giver has to /// veto when the Giver's delegates Pledge funds to a project /// @param oldPledge This value is used to store the pledge the current /// pledge was came from, and in the case a Project is canceled, the Pledge /// will revert back to it's previous state /// @param state The pledge state: Pledged, Paying, or state /// @return The hPledge2idx index number function _findOrCreatePledge( uint64 owner, uint64[] delegationChain, uint64 intendedProject, uint64 commitTime, uint64 oldPledge, address token, PledgeState state ) internal returns (uint64) { bytes32 hPledge = keccak256(abi.encodePacked(delegationChain, owner, intendedProject, commitTime, oldPledge, token, state)); uint64 id = hPledge2idx[hPledge]; if (id > 0) { return id; } id = uint64(pledges.length); hPledge2idx[hPledge] = id; pledges.push( Pledge( 0, delegationChain, owner, intendedProject, commitTime, oldPledge, token, state ) ); return id; } /// @param idPledge the id of the pledge to load from storage /// @return The Pledge function _findPledge(uint64 idPledge) internal view returns(Pledge storage) { require(idPledge < pledges.length); return pledges[idPledge]; } /// @notice A getter that searches the delegationChain for the level of /// authority a specific delegate has within a Pledge /// @param p The Pledge that will be searched /// @param idDelegate The specified delegate that's searched for /// @return If the delegate chain contains the delegate with the /// `admins` array index `idDelegate` this returns that delegates /// corresponding index in the delegationChain. Otherwise it returns /// the NOTFOUND constant function _getDelegateIdx(Pledge p, uint64 idDelegate) internal pure returns(uint64) { for (uint i = 0; i < p.delegationChain.length; i++) { if (p.delegationChain[i] == idDelegate) { return uint64(i); } } return NOTFOUND; } /// @notice A getter to find how many old "parent" pledges a specific Pledge /// had using a self-referential loop /// @param p The Pledge being queried /// @return The number of old "parent" pledges a specific Pledge had function _getPledgeLevel(Pledge p) internal view returns(uint) { if (p.oldPledge == 0) { return 0; } Pledge storage oldP = _findPledge(p.oldPledge); return _getPledgeLevel(oldP) + 1; // a loop lookup } }
A getter that searches the delegationChain for the level of authority a specific delegate has within a Pledge p The Pledge that will be searched idDelegate The specified delegate that's searched for return If the delegate chain contains the delegate with the `admins` array index `idDelegate` this returns that delegates corresponding index in the delegationChain. Otherwise it returns the NOTFOUND constant
function _getDelegateIdx(Pledge p, uint64 idDelegate) internal pure returns(uint64) { for (uint i = 0; i < p.delegationChain.length; i++) { if (p.delegationChain[i] == idDelegate) { return uint64(i); } } return NOTFOUND; }
6,368,907
pragma solidity ^0.4.22; import "../IDaoBase.sol"; import "./IVoting.sol"; import "./IProposal.sol"; import "./VotingLib.sol"; import "../tokens/StdDaoToken.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; // TODO Stacked voting: // 1 - client transfers N tokens for D days // 2 - client calls vote(_yes, _tokenAmount) // 3 - the result is calculated contract Voting is IVoting, Ownable { using VotingLib for VotingLib.VotingStorage; VotingLib.VotingStorage store; event Voted(address _who, bool _yes); event CallAction(); event DelegatedTo(address _sender, uint _tokensAmount); event DelegationRemoved(address _from, address _to); /* * @param _daoBase – DAO where proposal was created. * @param _proposal – proposal, which create vote. * @param _origin – who create voting (group member). * @param _minutesToVote - if is zero -> voting until quorum reached, else voting finish after minutesToVote minutes * @param _quorumPercent - percent of group members to make quorum reached. If minutesToVote==0 and quorum reached -> voting is finished * @param _consensusPercent - percent of voters (not of group members!) to make consensus reached. If consensus reached -> voting is finished with YES result * @param _votingType – one of the voting type, see enum votingType * @param _groupName – for votings that for daoBase group members only * @param _tokenAddress – for votings that uses token amount of voter */ constructor(IDaoBase _daoBase, IProposal _proposal, address _origin, VotingLib.VotingType _votingType, uint _minutesToVote, string _groupName, uint _quorumPercent, uint _consensusPercent, address _tokenAddress) public { store.generalConstructor( _daoBase, _proposal, _origin, _votingType, _minutesToVote, _groupName, _quorumPercent, _consensusPercent, _tokenAddress ); } /** * @return percent of group members to make quorum reached. * @dev If minutesToVote==0 and quorum reached -> voting is finished */ function quorumPercent() public view returns(uint) { return store.quorumPercent; } /** * @return percent of voters to make consensus reached * @dev If consensus reached -> voting is finished with YES result */ function consensusPercent() public view returns(uint) { return store.consensusPercent; } /** * @return name of group * @dev for votings that for daoBase group members only */ function groupName() public view returns(string) { return store.groupName; } /** * @return number of total voters */ function getVotersTotal() public view returns(uint) { return store.getVotersTotal(); } /** * @param _voter address of voter * @return power of voter */ function getPowerOf(address _voter) public view returns(uint) { return store.getPowerOf(_voter); } /** * @dev vote positive from the originator of the voting */ function voteFromOriginPositive() public { store.libVote(store.votingCreator, true); } /** * @param _isYes vote * @dev vote function */ function vote(bool _isYes) public { store.libVote(msg.sender, _isYes); } /** * @dev call action when voting finished with yes */ function callActionIfEnded() public { store.callActionIfEnded(); } /** * @return true if voting finished */ function isFinished() public view returns(bool) { return store.isFinished(); } /** * @return true if voting finished with yes */ function isYes() public view returns(bool) { return store.isYes(); } /** * @return amount of yes, no and voters total */ function getVotingStats() public view returns(uint yesResults, uint noResults, uint votersTotal) { return store.getVotingStats(); } /** * @notice This function should be called only by owner * @return cancel voting */ function cancelVoting() public onlyOwner { store.canceled = true; } // ------------------ LIQUID ------------------ /** * @param _of address * @return delegated power for account _of */ function getDelegatedPowerOf(address _of) public view returns(uint) { return store.getDelegatedPowerOf(_of); } /** * @param _to address * @return delegated power to account _to by msg.sender */ function getDelegatedPowerByMe(address _to) public view returns(uint) { return store.getDelegatedPowerByMe(_to); } /** * @param _to address * @param _tokenAmount amount of tokens which will be delegated * @dev delegate power to account _to by msg.sender */ function delegateMyVoiceTo(address _to, uint _tokenAmount) public { store.delegateMyVoiceTo(_to, _tokenAmount); } /** * @param _to address * @dev remove delegation for account _to */ function removeDelegation(address _to) public { store.removeDelegation(_to); } }
return true if voting finished with yes/
function isYes() public view returns(bool) { return store.isYes(); }
12,618,462
./partial_match/1/0xd156a09704171AFe371572D4Aece2F75112B9677/sources/src/GasTankModule.sol
Here is where the magic happens. Call `_safe` execTransaction and pull the fees from `_gasTank` to pay Gelato for relaying the transaction. Only GelatoRelayERC2771 contract can call this function. _gasTank A safe used as the gas tank from where the fees are pulled. The sender mut be an owner or a delegate. _safe The safe where the transaction is executed. _txData The contains the calldata used for calling execTransaction on the `_safe`. _maxFee The max allowed fee the sender is willing to pay, including the admin fee if it was enabled. _feeSignature The signature used for verifying that the sender agreed to pay the relaying fee using the `_gasTank`./
function execTransaction( address _gasTank, address _safe, bytes memory _txData, uint256 _maxFee, bytes memory _feeSignature ) public onlyGelatoRelayERC2771 returns (bool success) { (uint256 relayerFee, uint256 adminFeeAmount) = _payFees(_gasTank, _maxFee, _feeSignature); bool returnData = abi.decode(Address.functionCall(_safe, _txData), (bool)); emit ExecTransaction(_getMsgSender(), _gasTank, _safe, relayerFee, adminFeeAmount); return returnData; }
9,412,620
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) {// Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) {// Equivalent to !contains(map, key) map._entries.push(MapEntry({_key : key, _value : value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) {// Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: @openzeppelin/contracts/utils/Strings.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId,) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mecanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {} } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/common/AccessControlMixin.sol pragma solidity 0.6.6; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } // File: contracts/common/Initializable.sol pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity 0.6.6; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity 0.6.6; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce : nonces[userAddress], from : userAddress, functionSignature : functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: contracts/root/RootToken/IMintableERC721.sol pragma solidity 0.6.6; interface IMintableERC721 is IERC721 { /** * @notice called by predicate contract to mint tokens while withdrawing * @dev Should be callable only by MintableERC721Predicate * Make sure minting is done only by this function * @param user user address for whom token is being minted * @param tokenId tokenId being minted */ function mint(address user, uint256 tokenId) external; /** * @notice called by predicate contract to mint tokens while withdrawing with metadata from L2 * @dev Should be callable only by MintableERC721Predicate * Make sure minting is only done either by this function/ 👆 * @param user user address for whom token is being minted * @param tokenId tokenId being minted * @param metaData Associated token metadata, to be decoded & set using `setTokenMetadata` * * Note : If you're interested in taking token metadata from L2 to L1 during exit, you must * implement this method */ function mint(address user, uint256 tokenId, bytes calldata metaData) external; /** * @notice check if token already exists, return true if it does exist * @dev this check will be used by the predicate to determine if the token needs to be minted or transfered * @param tokenId tokenId being checked */ function exists(uint256 tokenId) external view returns (bool); } // File: contracts/common/ContextMixin.sol pragma solidity 0.6.6; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File: contracts/root/RootToken/DummyMintableERC721.sol pragma experimental ABIEncoderV2; pragma solidity 0.6.6; contract ArtvatarsMintableERC721 is ERC721, AccessControlMixin, NativeMetaTransaction, IMintableERC721, ContextMixin { bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE"); mapping(uint256 => Artvatar) public tokenToArtvatar; struct Attribute { string title; string name; } struct Artvatar { uint256 id; string series; string title; string description; string image; Attribute[] attributes; bool metadataChanged; } constructor(string memory name_, string memory symbol_, address predicateProxy_) public ERC721(name_, symbol_) { _setupContractId("ArtvatarsMintableERC721"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PREDICATE_ROLE, _msgSender()); _setupRole(PREDICATE_ROLE, predicateProxy_); _initializeEIP712(name_); } function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } /** * @dev See {IMintableERC721-mint}. */ function mint(address user, uint256 tokenId) external override only(PREDICATE_ROLE) { _mint(user, tokenId); } /** * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method, to be invoked * when minting token back on L1, during exit */ function setTokenMetadata(uint256 tokenId, bytes memory data) internal virtual { // This function should decode metadata obtained from L2 // and attempt to set it for this `tokenId` // // Following is just a default implementation, feel // free to define your own encoding/ decoding scheme // for L2 -> L1 token metadata transfer (Artvatar memory _artvatar, string memory uri) = abi.decode(data, (Artvatar, string)); Artvatar storage artvatar = tokenToArtvatar[tokenId]; Attribute[] memory _attributes = _artvatar.attributes; artvatar.id = _artvatar.id; artvatar.series = _artvatar.series; artvatar.title = _artvatar.title; artvatar.description = _artvatar.description; artvatar.image = _artvatar.image; for (uint256 i = 0; i < _attributes.length; i++) { Attribute memory attribute = _attributes[i]; artvatar.attributes.push(attribute); } artvatar.metadataChanged = true; _setTokenURI(tokenId, uri); } function getArtvatarByTokenId(uint256 _tokenId) public view returns (Artvatar memory artvatar) { return tokenToArtvatar[_tokenId]; } /** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */ function mint(address user, uint256 tokenId, bytes calldata metaData) external override only(PREDICATE_ROLE) { _mint(user, tokenId); setTokenMetadata(tokenId, metaData); } /** * @dev See {IMintableERC721-exists}. */ function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } }
Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but with `errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); }
1,139,760
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** “The following contract is quite complex, but showcases a lot of Solidity’s features. It implements a voting contract. Of course, the main problems of electronic voting is how to assign voting rights to the correct persons and how to prevent manipulation. We will not solve all problems here, but at least we will show how delegated voting can be done so that vote counting is automatic and completely transparent at the same time. The idea is to create one contract per ballot, providing a short name for each option. Then the creator of the contract who serves as chairperson will give the right to vote to each address individually. The persons behind the addresses can then choose to either vote themselves or to delegate their vote to a person they trust. At the end of the voting time, winningProposal() will return the proposal with the largest number of votes.” */ /// @title Voting with delegation. contract Ballot { // This declares a new complex type which will // be used for variables later. // It will represent a single voter. struct Voter { uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted address delegate; // person delegated to uint vote; // index of the voted proposal } // this is the type of single proposal struct Proposal { bytes32 name; // short name up to 32 bytes uint voteCount; // number of accumulated votes } address public chairperson; // This declares a state variable that // storws a 'Voter' struct for each possible address mapping(address => Voter) public voters; // A dynamically-sized array of 'Proposals' Proposal[] public proposals; // Create a new ballot to choose one of 'proposalNames' constructor(bytes32[] memory proposalNames) { chairperson = msg.sender; voters[chairperson].weight = 1; // For each of the provided proposal names, // create a new proposal object and add it // to the end of the array for (uint256 index = 0; index < proposalNames.length; index++) { // 'Proposal({...})' creates a temporary // Proposal object and 'proposals.push' // appends it to the end of 'propoals' proposals.push(Proposal({ name: proposalNames[index], voteCount: 0 })); } } // Give 'voter' the right to vote on this ballot // May only be called by 'chairperson function giveRightToVote(address voter) public { // If the first argument of 'require' evaluates // to 'fasle', execution terminates and all // changes to the state and to Ether ballances are reverted. // This used to cinsume all gass in old EVM versions, but not enymore. // It is often a good idea to use 'require' to check if // functions are called correctly // As a second argument, you can also provide an // explanation about what went wrong require(msg.sender == chairperson,'Only chairperson can give rights to vote'); require(!voters[voter].voted, 'The voter already voted'); require(voters[voter].weight == 0); voters[voter].weight = 1; } // Delegate your vote to the voter 'to' function delegate(address to) public { // assign reference Voter storage sender = voters[msg.sender]; require(!sender.voted, 'You already voted'); require(to != msg.sender, 'Self-delegation is not allowed'); // Forward the delegation as long as 'to' also delegated // In general, such loops are very dangerous // because if they run too long, they might // need more Gas than is available in a block. // In this case, the delegation will not be executed, // but in other situations, such loop might // cause a contract to get 'stuck' completely while (voters[to].delegate != address(0)) { to = voters[to].delegate; require(to !=msg.sender, 'Found loop in delegation'); // since 'sender' is a reference, this // modifies 'voters[msg.sender].voted' sender.voted = true; sender.delegate = to; Voter storage delegate_ = voters[to]; if (delegate_.voted) { // If the delegate already voted, // directly add the number of votes proposals[delegate_.vote].voteCount += sender.weight; }else{ // If the delegate did not vote yet, // add to his/her weight delegate_.weight += sender.weight; } } } // Give your vote (including votes delegated to you) // to proposal 'proposals[proposal].name' function vote(uint proposal) public { Voter storage sender = voters[msg.sender]; require(sender.weight != 0, 'Has no right to vote'); require(!sender.voted, 'Already voted'); sender.voted = true; sender.vote = proposal; // If 'proposal' is out if the range of the array // this will throw automatically and revert all changes proposals[proposal].voteCount += sender.weight; } // @dev Computes the winning proposal taing all // previous votes into account function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint256 index = 0; index < proposals.length; index++) { if (proposals[index].voteCount > winningVoteCount) { winningVoteCount = proposals[index].voteCount; winningProposal_ = index; } } } // Calls winningProposal() function to get the index // of the winner contained in the proposals array // and then returns the winner function winnerName() public view returns (bytes32 winnerName_) { winnerName_ = proposals[winningProposal()].name; } }
Give 'voter' the right to vote on this ballot May only be called by 'chairperson If the first argument of 'require' evaluates to 'fasle', execution terminates and all changes to the state and to Ether ballances are reverted. This used to cinsume all gass in old EVM versions, but not enymore. It is often a good idea to use 'require' to check if functions are called correctly As a second argument, you can also provide an explanation about what went wrong
function giveRightToVote(address voter) public { require(msg.sender == chairperson,'Only chairperson can give rights to vote'); require(!voters[voter].voted, 'The voter already voted'); require(voters[voter].weight == 0); voters[voter].weight = 1; }
13,077,639
./full_match/1/0x1B2Af52fC41EAbfFD8B245Ea834F633E929Ff93C/sources/contracts/Pills.sol
See {ERC721A - setApprovalForAll} and {DefaultOperatorFilterer - onlyAllowedOperatorApproval} Additional requirements: - transfer should be allowed/
function setApprovalForAll( address operator, bool approved ) public virtual override onlyAllowedOperatorApproval(operator) { ERC721A.setApprovalForAll(operator, approved); }
9,665,965
pragma solidity >=0.8.0; //created by lailaibtc //twitter:@lailaibtc //change the world together //Thanks everyone /** * @dev String operations. */ library Strings { bytes16 private constant _ALPHABET = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _ALPHABET[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721URIStorage: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721URIStorage: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked {counter._value += 1;} } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked {counter._value = value - 1;} } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked {_approve(sender, _msgSender(), currentAllowance - amount);} return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked {_balances[sender] = senderBalance - amount;} _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked {_balances[account] = accountBalance - amount;} _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require( currentAllowance >= amount, "ERC20: burn amount exceeds allowance" ); unchecked {_approve(account, _msgSender(), currentAllowance - amount);} _burn(account, amount); } } contract EMS is ERC20Burnable, Ownable { constructor() public ERC20("Ethereum Mail Service token", "EMS") {} function mint(address account, uint256 amount) public onlyOwner() { _mint(account, amount); } function decimals() public view virtual override returns (uint8) { return 8; } } contract EthereumMailService is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private tokenId; using SafeMath for uint256; EMS public ems; event Post(string ipfsHash); event Like(uint256 _tokenId); event Comment(uint256 _tokenId, string ipfsHash); event Remail(uint256 _tokenId); event GenNFT(uint256 _tokenId,string ipfsHash); mapping(address => uint256[]) public mails; mapping(address => uint256[]) public likes; mapping(address => uint256[]) public commentsValueIndex; mapping(address => mapping(uint256 => uint256[])) public comments; mapping(address => uint256[]) public remails; mapping(uint256 => uint256) public mailLikes; mapping(uint256 => uint256[]) public mailComments; mapping(uint256 => uint256) public mailRemails; constructor(EMS _ems) public ERC721("Ethereum Mail Service", "EMS") { ems = _ems; } function getMintBase() public view returns (uint256) { uint256 left = 210000000000 * 10**ems.decimals() - ems.totalSupply(); return left.div(10**4); } function post(string memory _ipfsHash) public { tokenId.increment(); mails[msg.sender].push(tokenId.current()); _genNFT(tokenId.current(), _ipfsHash); uint256 base = getMintBase(); _mintEMS(msg.sender, base); emit Post(_ipfsHash); } function _genNFT(uint256 _tokenId, string memory _ipfsHash) internal { _safeMint(msg.sender, _tokenId); _setTokenURI(_tokenId, _ipfsHash); emit GenNFT(_tokenId, _ipfsHash); } function like(uint256 _tokenId) public { likes[msg.sender].push(_tokenId); mailLikes[_tokenId] = mailLikes[_tokenId].add(1); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Like(_tokenId); } function comment(uint256 _tokenId, string memory _ipfsHash) public { tokenId.increment(); _genNFT(tokenId.current(), _ipfsHash); comments[msg.sender][_tokenId].push(tokenId.current()); if (comments[msg.sender][_tokenId].length == 1) { commentsValueIndex[msg.sender].push(_tokenId); } mailComments[_tokenId].push(tokenId.current()); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Comment(_tokenId, _ipfsHash); } function remail(uint256 _tokenId) public { remails[msg.sender].push(_tokenId); mailRemails[_tokenId] = mailRemails[_tokenId].add(1); uint256 base = getMintBase(); _mintEMS(msg.sender, base.div(2)); _mintEMS(ownerOf(_tokenId), base.div(2)); emit Remail(_tokenId); } function _mintEMS(address _account, uint256 _amount) internal { ems.mint(_account, _amount); } function getMailsLength(address _account) public view returns (uint256) { return mails[_account].length; } function getLikesLength(address _account) public view returns (uint256) { return likes[_account].length; } function getCommentsValueIndexLength(address _account) public view returns (uint256) { return commentsValueIndex[_account].length; } function getCommentsLength(address _account, uint256 _tokenId) public view returns (uint256) { return comments[_account][_tokenId].length; } function getRemailsLength(address _account) public view returns (uint256) { return remails[_account].length; } function getMailCommentsLength(uint256 _tokenId) public view returns (uint256) { return mailComments[_tokenId].length; } }
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] += amount; emit Transfer(sender, recipient, amount); }
1,400,264
./full_match/1/0xbf71d25d74A1428aaa4FA84AAE595D8a26b960db/sources/contracts/TokenLock/TokenLock.sol
Returns the current block timestamp return Current block timestamp/
function currentTime() public view override returns (uint256) { return block.timestamp; }
2,977,472
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/IMonethaVoucher.sol interface IMonethaVoucher { /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256); /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers (vouchers) to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256); /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers (vouchers) * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256); /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei); /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers); /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external payable; /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external returns(uint256 weis); /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external returns (bool); /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256); } // File: monetha-utility-contracts/contracts/Restricted.sol /** @title Restricted * Exposes onlyMonetha modifier */ contract Restricted is Ownable { //MonethaAddress set event event MonethaAddressSet( address _address, bool _isMonethaAddress ); mapping (address => bool) public isMonethaAddress; /** * Restrict methods in such way, that they can be invoked only by monethaAddress account. */ modifier onlyMonetha() { require(isMonethaAddress[msg.sender]); _; } /** * Allows owner to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); } } // File: contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/ownership/CanReclaimEther.sol contract CanReclaimEther is Ownable { event ReclaimEther(address indexed to, uint256 amount); /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { uint256 value = address(this).balance; owner.transfer(value); emit ReclaimEther(owner, value); } /** * @dev Transfer specified amount of Ether held by the contract to the address. * @param _to The address which will receive the Ether * @param _value The amount of Ether to transfer */ function reclaimEtherTo(address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _to.transfer(_value); emit ReclaimEther(_to, _value); } } // File: contracts/ownership/CanReclaimTokens.sol contract CanReclaimTokens is Ownable { using SafeERC20 for ERC20Basic; event ReclaimTokens(address indexed to, uint256 amount); /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); emit ReclaimTokens(owner, balance); } /** * @dev Reclaim specified amount of ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract * @param _to The address which will receive the tokens * @param _value The amount of tokens to transfer */ function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _token.safeTransfer(_to, _value); emit ReclaimTokens(_to, _value); } } // File: contracts/MonethaVoucher.sol contract MonethaVoucher is IMonethaVoucher, Restricted, Pausable, IERC20, CanReclaimEther, CanReclaimTokens { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event DiscountApplied(address indexed user, uint256 releasedVouchers, uint256 amountWeiTransferred); event PaybackApplied(address indexed user, uint256 addedVouchers, uint256 amountWeiEquivalent); event VouchersBought(address indexed user, uint256 vouchersBought); event VouchersSold(address indexed user, uint256 vouchersSold, uint256 amountWeiTransferred); event VoucherMthRateUpdated(uint256 oldVoucherMthRate, uint256 newVoucherMthRate); event MthEthRateUpdated(uint256 oldMthEthRate, uint256 newMthEthRate); event VouchersAdded(address indexed user, uint256 vouchersAdded); event VoucherReleased(address indexed user, uint256 releasedVoucher); event PurchasedVouchersReleased(address indexed from, address indexed to, uint256 vouchers); /* Public variables of the token */ string constant public standard = "ERC20"; string constant public name = "Monetha Voucher"; string constant public symbol = "MTHV"; uint8 constant public decimals = 5; /* For calculating half year */ uint256 constant private DAY_IN_SECONDS = 86400; uint256 constant private YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS; uint256 constant private LEAP_YEAR_IN_SECONDS = 366 * DAY_IN_SECONDS; uint256 constant private YEAR_IN_SECONDS_AVG = (YEAR_IN_SECONDS * 3 + LEAP_YEAR_IN_SECONDS) / 4; uint256 constant private HALF_YEAR_IN_SECONDS_AVG = YEAR_IN_SECONDS_AVG / 2; uint256 constant public RATE_COEFFICIENT = 1000000000000000000; // 10^18 uint256 constant private RATE_COEFFICIENT2 = RATE_COEFFICIENT * RATE_COEFFICIENT; // RATE_COEFFICIENT^2 uint256 public voucherMthRate; // number of voucher units in 10^18 MTH units uint256 public mthEthRate; // number of mth units in 10^18 wei uint256 internal voucherMthEthRate; // number of vouchers units (= voucherMthRate * mthEthRate) in 10^36 wei ERC20Basic public mthToken; mapping(address => uint256) public purchased; // amount of vouchers purchased by other monetha contract uint256 public totalPurchased; // total amount of vouchers purchased by monetha mapping(uint16 => uint256) public totalDistributedIn; // аmount of vouchers distributed in specific half-year mapping(uint16 => mapping(address => uint256)) public distributed; // amount of vouchers distributed in specific half-year to specific user constructor(uint256 _voucherMthRate, uint256 _mthEthRate, ERC20Basic _mthToken) public { require(_voucherMthRate > 0, "voucherMthRate should be greater than 0"); require(_mthEthRate > 0, "mthEthRate should be greater than 0"); require(_mthToken != address(0), "must be valid contract"); voucherMthRate = _voucherMthRate; mthEthRate = _mthEthRate; mthToken = _mthToken; _updateVoucherMthEthRate(); } /** * @dev Total number of vouchers in existence = vouchers in shared pool + vouchers distributed + vouchers purchased */ function totalSupply() external view returns (uint256) { return _totalVouchersSupply(); } /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256) { return _vouchersInSharedPool(_currentHalfYear()); } /** * @dev Total number of vouchers distributed */ function totalDistributed() external view returns (uint256) { return _vouchersDistributed(_currentHalfYear()); } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) external view returns (uint256) { return _distributedTo(owner, _currentHalfYear()).add(purchased[owner]); } /** * @dev Function to check the amount of vouchers that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of vouchers still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { owner; spender; return 0; } /** * @dev Transfer voucher for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) external returns (bool) { to; value; revert(); } /** * @dev Approve the passed address to spend the specified amount of vouchers on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of vouchers to be spent. */ function approve(address spender, uint256 value) external returns (bool) { spender; value; revert(); } /** * @dev Transfer vouchers from one address to another * @param from address The address which you want to send vouchers from * @param to address The address which you want to transfer to * @param value uint256 the amount of vouchers to be transferred */ function transferFrom(address from, address to, uint256 value) external returns (bool) { from; to; value; revert(); } // Allows direct funds send by Monetha function () external onlyMonetha payable { } /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256) { return _vouchersToWei(_value); } /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256) { return _weiToVouchers(_value); } /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) { require(_for != address(0), "zero address is not allowed"); uint256 releasedVouchers = _releaseVouchers(_for, _vouchers); if (releasedVouchers == 0) { return (0,0); } uint256 amountToTransfer = _vouchersToWei(releasedVouchers); require(address(this).balance >= amountToTransfer, "insufficient funds"); _for.transfer(amountToTransfer); emit DiscountApplied(_for, releasedVouchers, amountToTransfer); return (releasedVouchers, amountToTransfer); } /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external onlyMonetha returns (uint256 amountVouchers) { amountVouchers = _weiToVouchers(_amountWei); require(_addVouchers(_for, amountVouchers), "vouchers must be added"); emit PaybackApplied(_for, amountVouchers, _amountWei); } /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external onlyMonetha payable { uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _vouchers, "insufficient vouchers present"); require(msg.value == _vouchersToWei(_vouchers), "insufficient funds"); _addPurchasedTo(msg.sender, _vouchers); emit VouchersBought(msg.sender, _vouchers); } /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) { require(_vouchers <= purchased[msg.sender], "Insufficient vouchers"); _subPurchasedFrom(msg.sender, _vouchers); weis = _vouchersToWei(_vouchers); msg.sender.transfer(weis); emit VouchersSold(msg.sender, _vouchers, weis); } /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) { require(_value <= purchased[msg.sender], "Insufficient Vouchers"); require(_to != address(0), "address should be valid"); _subPurchasedFrom(msg.sender, _value); _addVouchers(_to, _value); emit PurchasedVouchersReleased(msg.sender, _to, _value); return true; } /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256) { return purchased[owner]; } /** * @dev updates voucherMthRate. */ function updateVoucherMthRate(uint256 _voucherMthRate) external onlyMonetha { require(_voucherMthRate > 0, "should be greater than 0"); require(voucherMthRate != _voucherMthRate, "same as previous value"); voucherMthRate = _voucherMthRate; _updateVoucherMthEthRate(); emit VoucherMthRateUpdated(voucherMthRate, _voucherMthRate); } /** * @dev updates mthEthRate. */ function updateMthEthRate(uint256 _mthEthRate) external onlyMonetha { require(_mthEthRate > 0, "should be greater than 0"); require(mthEthRate != _mthEthRate, "same as previous value"); mthEthRate = _mthEthRate; _updateVoucherMthEthRate(); emit MthEthRateUpdated(mthEthRate, _mthEthRate); } function _addPurchasedTo(address _to, uint256 _value) internal { purchased[_to] = purchased[_to].add(_value); totalPurchased = totalPurchased.add(_value); } function _subPurchasedFrom(address _from, uint256 _value) internal { purchased[_from] = purchased[_from].sub(_value); totalPurchased = totalPurchased.sub(_value); } function _updateVoucherMthEthRate() internal { voucherMthEthRate = voucherMthRate.mul(mthEthRate); } /** * @dev Transfer vouchers from shared pool to address. May be called only by Monetha. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _addVouchers(address _to, uint256 _value) internal returns (bool) { require(_to != address(0), "zero address is not allowed"); uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _value, "must be less or equal than vouchers present in shared pool"); uint256 oldDist = totalDistributedIn[currentHalfYear]; totalDistributedIn[currentHalfYear] = oldDist.add(_value); uint256 oldBalance = distributed[currentHalfYear][_to]; distributed[currentHalfYear][_to] = oldBalance.add(_value); emit VouchersAdded(_to, _value); return true; } /** * @dev Transfer vouchers from address to shared pool * @param _from address The address which you want to send vouchers from * @param _value uint256 the amount of vouchers to be transferred * @return A uint256 specifying the amount of vouchers released to shared pool. */ function _releaseVouchers(address _from, uint256 _value) internal returns (uint256) { require(_from != address(0), "must be valid address"); uint16 currentHalfYear = _currentHalfYear(); uint256 released = 0; if (currentHalfYear > 0) { released = released.add(_releaseVouchers(_from, _value, currentHalfYear - 1)); _value = _value.sub(released); } released = released.add(_releaseVouchers(_from, _value, currentHalfYear)); emit VoucherReleased(_from, released); return released; } function _releaseVouchers(address _from, uint256 _value, uint16 _currentHalfYear) internal returns (uint256) { if (_value == 0) { return 0; } uint256 oldBalance = distributed[_currentHalfYear][_from]; uint256 subtracted = _value; if (oldBalance <= _value) { delete distributed[_currentHalfYear][_from]; subtracted = oldBalance; } else { distributed[_currentHalfYear][_from] = oldBalance.sub(_value); } uint256 oldDist = totalDistributedIn[_currentHalfYear]; if (oldDist == subtracted) { delete totalDistributedIn[_currentHalfYear]; } else { totalDistributedIn[_currentHalfYear] = oldDist.sub(subtracted); } return subtracted; } // converts vouchers to Ether (in wei) function _vouchersToWei(uint256 _value) internal view returns (uint256) { return _value.mul(RATE_COEFFICIENT2).div(voucherMthEthRate); } // converts Ether (in wei) to vouchers function _weiToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthEthRate).div(RATE_COEFFICIENT2); } // converts MTH tokens to vouchers function _mthToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthRate).div(RATE_COEFFICIENT); } // converts Ether (in wei) to MTH function _weiToMth(uint256 _value) internal view returns (uint256) { return _value.mul(mthEthRate).div(RATE_COEFFICIENT); } function _totalVouchersSupply() internal view returns (uint256) { return _mthToVouchers(mthToken.balanceOf(address(this))); } function _vouchersInSharedPool(uint16 _currentHalfYear) internal view returns (uint256) { return _totalVouchersSupply().sub(_vouchersDistributed(_currentHalfYear)).sub(totalPurchased); } function _vouchersDistributed(uint16 _currentHalfYear) internal view returns (uint256) { uint256 dist = totalDistributedIn[_currentHalfYear]; if (_currentHalfYear > 0) { // include previous half-year dist = dist.add(totalDistributedIn[_currentHalfYear - 1]); } return dist; } function _distributedTo(address _owner, uint16 _currentHalfYear) internal view returns (uint256) { uint256 balance = distributed[_currentHalfYear][_owner]; if (_currentHalfYear > 0) { // include previous half-year balance = balance.add(distributed[_currentHalfYear - 1][_owner]); } return balance; } function _currentHalfYear() internal view returns (uint16) { return uint16(now / HALF_YEAR_IN_SECONDS_AVG); } }
Allows direct funds send by Monetha
function () external onlyMonetha payable { }
1,015,233
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import {ERC721HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {ILendPool} from "../interfaces/ILendPool.sol"; import {ILendPoolLoan} from "../interfaces/ILendPoolLoan.sol"; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {IPunks} from "../interfaces/IPunks.sol"; import {IWrappedPunks} from "../interfaces/IWrappedPunks.sol"; import {IPunkGateway} from "../interfaces/IPunkGateway.sol"; import {DataTypes} from "../libraries/types/DataTypes.sol"; import {IWETHGateway} from "../interfaces/IWETHGateway.sol"; import {EmergencyTokenRecoveryUpgradeable} from "./EmergencyTokenRecoveryUpgradeable.sol"; contract PunkGateway is IPunkGateway, ERC721HolderUpgradeable, EmergencyTokenRecoveryUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; ILendPoolAddressesProvider internal _addressProvider; IWETHGateway internal _wethGateway; IPunks public punks; IWrappedPunks public wrappedPunks; address public proxy; mapping(address => bool) internal _callerWhitelists; function initialize( address addressProvider, address wethGateway, address _punks, address _wrappedPunks ) public initializer { __ERC721Holder_init(); __EmergencyTokenRecovery_init(); _addressProvider = ILendPoolAddressesProvider(addressProvider); _wethGateway = IWETHGateway(wethGateway); punks = IPunks(_punks); wrappedPunks = IWrappedPunks(_wrappedPunks); wrappedPunks.registerProxy(); proxy = wrappedPunks.proxyInfo(address(this)); IERC721Upgradeable(address(wrappedPunks)).setApprovalForAll(address(_getLendPool()), true); IERC721Upgradeable(address(wrappedPunks)).setApprovalForAll(address(_wethGateway), true); } function _getLendPool() internal view returns (ILendPool) { return ILendPool(_addressProvider.getLendPool()); } function _getLendPoolLoan() internal view returns (ILendPoolLoan) { return ILendPoolLoan(_addressProvider.getLendPoolLoan()); } function authorizeLendPoolERC20(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { IERC20Upgradeable(tokens[i]).approve(address(_getLendPool()), type(uint256).max); } } function authorizeCallerWhitelist(address[] calldata callers, bool flag) external onlyOwner { for (uint256 i = 0; i < callers.length; i++) { _callerWhitelists[callers[i]] = flag; } } function isCallerInWhitelist(address caller) external view returns (bool) { return _callerWhitelists[caller]; } function _checkValidCallerAndOnBehalfOf(address onBehalfOf) internal view { require( (onBehalfOf == _msgSender()) || (_callerWhitelists[_msgSender()] == true), Errors.CALLER_NOT_ONBEHALFOF_OR_IN_WHITELIST ); } function _depositPunk(uint256 punkIndex) internal { ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); if (loanId != 0) { return; } address owner = punks.punkIndexToAddress(punkIndex); require(owner == _msgSender(), "PunkGateway: not owner of punkIndex"); punks.buyPunk(punkIndex); punks.transferPunk(proxy, punkIndex); wrappedPunks.mint(punkIndex); } function borrow( address reserveAsset, uint256 amount, uint256 punkIndex, address onBehalfOf, uint16 referralCode ) external override { _checkValidCallerAndOnBehalfOf(onBehalfOf); ILendPool cachedPool = _getLendPool(); _depositPunk(punkIndex); cachedPool.borrow(reserveAsset, amount, address(wrappedPunks), punkIndex, onBehalfOf, referralCode); IERC20Upgradeable(reserveAsset).transfer(onBehalfOf, amount); } function _withdrawPunk(uint256 punkIndex, address onBehalfOf) internal { address owner = wrappedPunks.ownerOf(punkIndex); require(owner == _msgSender(), "PunkGateway: caller is not owner"); require(owner == onBehalfOf, "PunkGateway: onBehalfOf is not owner"); wrappedPunks.safeTransferFrom(onBehalfOf, address(this), punkIndex); wrappedPunks.burn(punkIndex); punks.transferPunk(onBehalfOf, punkIndex); } function repay(uint256 punkIndex, uint256 amount) external override returns (uint256, bool) { ILendPool cachedPool = _getLendPool(); ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); (, , address reserve, ) = cachedPoolLoan.getLoanCollateralAndReserve(loanId); (, uint256 debt) = cachedPoolLoan.getLoanReserveBorrowAmount(loanId); address borrower = cachedPoolLoan.borrowerOf(loanId); if (amount > debt) { amount = debt; } IERC20Upgradeable(reserve).transferFrom(msg.sender, address(this), amount); (uint256 paybackAmount, bool burn) = cachedPool.repay(address(wrappedPunks), punkIndex, amount); if (burn) { require(borrower == _msgSender(), "PunkGateway: caller is not borrower"); _withdrawPunk(punkIndex, borrower); } return (paybackAmount, burn); } function auction( uint256 punkIndex, uint256 bidPrice, address onBehalfOf ) external override { _checkValidCallerAndOnBehalfOf(onBehalfOf); ILendPool cachedPool = _getLendPool(); ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); (, , address reserve, ) = cachedPoolLoan.getLoanCollateralAndReserve(loanId); IERC20Upgradeable(reserve).transferFrom(msg.sender, address(this), bidPrice); cachedPool.auction(address(wrappedPunks), punkIndex, bidPrice, onBehalfOf); } function redeem(uint256 punkIndex, uint256 amount) external override returns (uint256) { ILendPool cachedPool = _getLendPool(); ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); DataTypes.LoanData memory loan = cachedPoolLoan.getLoan(loanId); IERC20Upgradeable(loan.reserveAsset).transferFrom(msg.sender, address(this), amount); uint256 paybackAmount = cachedPool.redeem(address(wrappedPunks), punkIndex, amount); if (amount > paybackAmount) { IERC20Upgradeable(loan.reserveAsset).safeTransfer(msg.sender, (amount - paybackAmount)); } return paybackAmount; } function liquidate(uint256 punkIndex, uint256 amount) external override returns (uint256) { ILendPool cachedPool = _getLendPool(); ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); DataTypes.LoanData memory loan = cachedPoolLoan.getLoan(loanId); require(loan.bidderAddress == _msgSender(), "PunkGateway: caller is not bidder"); if (amount > 0) { IERC20Upgradeable(loan.reserveAsset).transferFrom(msg.sender, address(this), amount); } uint256 extraRetAmount = cachedPool.liquidate(address(wrappedPunks), punkIndex, amount); _withdrawPunk(punkIndex, loan.bidderAddress); if (amount > extraRetAmount) { IERC20Upgradeable(loan.reserveAsset).safeTransfer(msg.sender, (amount - extraRetAmount)); } return (extraRetAmount); } function borrowETH( uint256 amount, uint256 punkIndex, address onBehalfOf, uint16 referralCode ) external override { _checkValidCallerAndOnBehalfOf(onBehalfOf); _depositPunk(punkIndex); _wethGateway.borrowETH(amount, address(wrappedPunks), punkIndex, onBehalfOf, referralCode); } function repayETH(uint256 punkIndex, uint256 amount) external payable override returns (uint256, bool) { ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); address borrower = cachedPoolLoan.borrowerOf(loanId); (uint256 paybackAmount, bool burn) = _wethGateway.repayETH{value: msg.value}( address(wrappedPunks), punkIndex, amount ); if (burn) { require(borrower == _msgSender(), "PunkGateway: caller is not borrower"); _withdrawPunk(punkIndex, borrower); } // refund remaining dust eth if (msg.value > paybackAmount) { _safeTransferETH(msg.sender, msg.value - paybackAmount); } return (paybackAmount, burn); } function auctionETH(uint256 punkIndex, address onBehalfOf) external payable override { _checkValidCallerAndOnBehalfOf(onBehalfOf); _wethGateway.auctionETH{value: msg.value}(address(wrappedPunks), punkIndex, onBehalfOf); } function redeemETH(uint256 punkIndex, uint256 amount) external payable override returns (uint256) { ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); //DataTypes.LoanData memory loan = cachedPoolLoan.getLoan(loanId); uint256 paybackAmount = _wethGateway.redeemETH{value: msg.value}(address(wrappedPunks), punkIndex, amount); // refund remaining dust eth if (msg.value > paybackAmount) { _safeTransferETH(msg.sender, msg.value - paybackAmount); } return paybackAmount; } function liquidateETH(uint256 punkIndex) external payable override returns (uint256) { ILendPoolLoan cachedPoolLoan = _getLendPoolLoan(); uint256 loanId = cachedPoolLoan.getCollateralLoanId(address(wrappedPunks), punkIndex); require(loanId != 0, "PunkGateway: no loan with such punkIndex"); DataTypes.LoanData memory loan = cachedPoolLoan.getLoan(loanId); require(loan.bidderAddress == _msgSender(), "PunkGateway: caller is not bidder"); uint256 extraAmount = _wethGateway.liquidateETH{value: msg.value}(address(wrappedPunks), punkIndex); _withdrawPunk(punkIndex, loan.bidderAddress); // refund remaining dust eth if (msg.value > extraAmount) { _safeTransferETH(msg.sender, msg.value - extraAmount); } return extraAmount; } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); } /** * @dev */ receive() external payable {} /** * @dev Revert fallback calls */ fallback() external payable { revert("Fallback not allowed"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal onlyInitializing { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal onlyInitializing { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title Errors library * @author Bend * @notice Defines the error messages emitted by the different contracts of the Bend protocol */ library Errors { enum ReturnCode { SUCCESS, FAILED } string public constant SUCCESS = "0"; //common errors string public constant CALLER_NOT_POOL_ADMIN = "100"; // 'The caller must be the pool admin' string public constant CALLER_NOT_ADDRESS_PROVIDER = "101"; string public constant INVALID_FROM_BALANCE_AFTER_TRANSFER = "102"; string public constant INVALID_TO_BALANCE_AFTER_TRANSFER = "103"; string public constant CALLER_NOT_ONBEHALFOF_OR_IN_WHITELIST = "104"; //math library erros string public constant MATH_MULTIPLICATION_OVERFLOW = "200"; string public constant MATH_ADDITION_OVERFLOW = "201"; string public constant MATH_DIVISION_BY_ZERO = "202"; //validation & check errors string public constant VL_INVALID_AMOUNT = "301"; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = "302"; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = "303"; // 'Action cannot be performed because the reserve is frozen' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "304"; // 'User cannot withdraw more than the available balance' string public constant VL_BORROWING_NOT_ENABLED = "305"; // 'Borrowing is not enabled' string public constant VL_COLLATERAL_BALANCE_IS_0 = "306"; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "307"; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "308"; // 'There is not enough collateral to cover a new borrow' string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "309"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_ACTIVE_NFT = "310"; string public constant VL_NFT_FROZEN = "311"; string public constant VL_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "312"; // 'User did not borrow the specified currency' string public constant VL_INVALID_HEALTH_FACTOR = "313"; string public constant VL_INVALID_ONBEHALFOF_ADDRESS = "314"; string public constant VL_INVALID_TARGET_ADDRESS = "315"; string public constant VL_INVALID_RESERVE_ADDRESS = "316"; string public constant VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER = "317"; string public constant VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER = "318"; string public constant VL_HEALTH_FACTOR_HIGHER_THAN_LIQUIDATION_THRESHOLD = "319"; //lend pool errors string public constant LP_CALLER_NOT_LEND_POOL_CONFIGURATOR = "400"; // 'The caller of the function is not the lending pool configurator' string public constant LP_IS_PAUSED = "401"; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = "402"; string public constant LP_NOT_CONTRACT = "403"; string public constant LP_BORROW_NOT_EXCEED_LIQUIDATION_THRESHOLD = "404"; string public constant LP_BORROW_IS_EXCEED_LIQUIDATION_PRICE = "405"; string public constant LP_NO_MORE_NFTS_ALLOWED = "406"; string public constant LP_INVALIED_USER_NFT_AMOUNT = "407"; string public constant LP_INCONSISTENT_PARAMS = "408"; string public constant LP_NFT_IS_NOT_USED_AS_COLLATERAL = "409"; string public constant LP_CALLER_MUST_BE_AN_BTOKEN = "410"; string public constant LP_INVALIED_NFT_AMOUNT = "411"; string public constant LP_NFT_HAS_USED_AS_COLLATERAL = "412"; string public constant LP_DELEGATE_CALL_FAILED = "413"; string public constant LP_AMOUNT_LESS_THAN_EXTRA_DEBT = "414"; string public constant LP_AMOUNT_LESS_THAN_REDEEM_THRESHOLD = "415"; //lend pool loan errors string public constant LPL_INVALID_LOAN_STATE = "480"; string public constant LPL_INVALID_LOAN_AMOUNT = "481"; string public constant LPL_INVALID_TAKEN_AMOUNT = "482"; string public constant LPL_AMOUNT_OVERFLOW = "483"; string public constant LPL_BID_PRICE_LESS_THAN_LIQUIDATION_PRICE = "484"; string public constant LPL_BID_PRICE_LESS_THAN_HIGHEST_PRICE = "485"; string public constant LPL_BID_REDEEM_DURATION_HAS_END = "486"; string public constant LPL_BID_USER_NOT_SAME = "487"; string public constant LPL_BID_REPAY_AMOUNT_NOT_ENOUGH = "488"; string public constant LPL_BID_AUCTION_DURATION_HAS_END = "489"; string public constant LPL_BID_AUCTION_DURATION_NOT_END = "490"; string public constant LPL_BID_PRICE_LESS_THAN_BORROW = "491"; string public constant LPL_INVALID_BIDDER_ADDRESS = "492"; string public constant LPL_AMOUNT_LESS_THAN_BID_FINE = "493"; //common token errors string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool' string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = "503"; //reserve logic errors string public constant RL_RESERVE_ALREADY_INITIALIZED = "601"; // 'Reserve has already been initialized' string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "602"; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "603"; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = "604"; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "605"; // Variable borrow rate overflows uint128 //configure errors string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "700"; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = "701"; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "702"; // 'The caller must be the emergency admin' string public constant LPC_INVALIED_BNFT_ADDRESS = "703"; string public constant LPC_INVALIED_LOAN_ADDRESS = "704"; string public constant LPC_NFT_LIQUIDITY_NOT_0 = "705"; //reserve config errors string public constant RC_INVALID_LTV = "730"; string public constant RC_INVALID_LIQ_THRESHOLD = "731"; string public constant RC_INVALID_LIQ_BONUS = "732"; string public constant RC_INVALID_DECIMALS = "733"; string public constant RC_INVALID_RESERVE_FACTOR = "734"; string public constant RC_INVALID_REDEEM_DURATION = "735"; string public constant RC_INVALID_AUCTION_DURATION = "736"; string public constant RC_INVALID_REDEEM_FINE = "737"; string public constant RC_INVALID_REDEEM_THRESHOLD = "738"; //address provider erros string public constant LPAPR_PROVIDER_NOT_REGISTERED = "760"; // 'Provider is not registered' string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "761"; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol"; import {DataTypes} from "../libraries/types/DataTypes.sol"; interface ILendPool { /** * @dev Emitted on deposit() * @param user The address initiating the deposit * @param amount The amount deposited * @param reserve The address of the underlying asset of the reserve * @param onBehalfOf The beneficiary of the deposit, receiving the bTokens * @param referral The referral code used **/ event Deposit( address user, address indexed reserve, uint256 amount, address indexed onBehalfOf, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param user The address initiating the withdrawal, owner of bTokens * @param reserve The address of the underlyng asset being withdrawn * @param amount The amount to be withdrawn * @param to Address that will receive the underlying **/ event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to); /** * @dev Emitted on borrow() when loan needs to be opened * @param user The address of the user initiating the borrow(), receiving the funds * @param reserve The address of the underlying asset being borrowed * @param amount The amount borrowed out * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param onBehalfOf The address that will be getting the loan * @param referral The referral code used **/ event Borrow( address user, address indexed reserve, uint256 amount, address nftAsset, uint256 nftTokenId, address indexed onBehalfOf, uint256 borrowRate, uint256 loanId, uint16 indexed referral ); /** * @dev Emitted on repay() * @param user The address of the user initiating the repay(), providing the funds * @param reserve The address of the underlying asset of the reserve * @param amount The amount repaid * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param borrower The beneficiary of the repayment, getting his debt reduced * @param loanId The loan ID of the NFT loans **/ event Repay( address user, address indexed reserve, uint256 amount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when a borrower's loan is auctioned. * @param user The address of the user initiating the auction * @param reserve The address of the underlying asset of the reserve * @param bidPrice The price of the underlying reserve given by the bidder * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param onBehalfOf The address that will be getting the NFT * @param loanId The loan ID of the NFT loans **/ event Auction( address user, address indexed reserve, uint256 bidPrice, address indexed nftAsset, uint256 nftTokenId, address onBehalfOf, address indexed borrower, uint256 loanId ); /** * @dev Emitted on redeem() * @param user The address of the user initiating the redeem(), providing the funds * @param reserve The address of the underlying asset of the reserve * @param borrowAmount The borrow amount repaid * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param loanId The loan ID of the NFT loans **/ event Redeem( address user, address indexed reserve, uint256 borrowAmount, uint256 fineAmount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when a borrower's loan is liquidated. * @param user The address of the user initiating the auction * @param reserve The address of the underlying asset of the reserve * @param repayAmount The amount of reserve repaid by the liquidator * @param remainAmount The amount of reserve received by the borrower * @param loanId The loan ID of the NFT loans **/ event Liquidate( address user, address indexed reserve, uint256 repayAmount, uint256 remainAmount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendPool contract. The event is therefore replicated here so it * gets added to the LendPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens. * - E.g. User deposits 100 USDC and gets in return 100 bUSDC * @param reserve The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of bTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned * E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC * @param reserve The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole bToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address reserve, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet * and lock collateral asset in contract * @param reserveAsset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function borrow( address reserveAsset, uint256 amount, address nftAsset, uint256 nftTokenId, address onBehalfOf, uint16 referralCode ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay * @return The final amount repaid, loan is burned or not **/ function repay( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256, bool); /** * @dev Function to auction a non-healthy position collateral-wise * - The caller (liquidator) want to buy collateral asset of the user getting liquidated * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param bidPrice The bid price of the liquidator want to buy the underlying NFT * @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of NFT * is a different wallet **/ function auction( address nftAsset, uint256 nftTokenId, uint256 bidPrice, address onBehalfOf ) external; /** * @notice Redeem a NFT loan which state is in Auction * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay the debt and bid fine **/ function redeem( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256); /** * @dev Function to liquidate a non-healthy position collateral-wise * - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives * the collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral **/ function liquidate( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256); /** * @dev Validates and finalizes an bToken transfer * - Only callable by the overlying bToken of the `asset` * @param asset The address of the underlying asset of the bToken * @param from The user from which the bTokens are transferred * @param to The user receiving the bTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The bToken balance of the `from` user before the transfer * @param balanceToBefore The bToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external view; function getReserveConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); function getNftConfiguration(address asset) external view returns (DataTypes.NftConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function getReservesList() external view returns (address[] memory); function getNftData(address asset) external view returns (DataTypes.NftData memory); /** * @dev Returns the loan data of the NFT * @param nftAsset The address of the NFT * @param reserveAsset The address of the Reserve * @return totalCollateralInETH the total collateral in ETH of the NFT * @return totalCollateralInReserve the total collateral in Reserve of the NFT * @return availableBorrowsInETH the borrowing power in ETH of the NFT * @return availableBorrowsInReserve the borrowing power in Reserve of the NFT * @return ltv the loan to value of the user * @return liquidationThreshold the liquidation threshold of the NFT * @return liquidationBonus the liquidation bonus of the NFT **/ function getNftCollateralData(address nftAsset, address reserveAsset) external view returns ( uint256 totalCollateralInETH, uint256 totalCollateralInReserve, uint256 availableBorrowsInETH, uint256 availableBorrowsInReserve, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Returns the debt data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return reserveAsset the address of the Reserve * @return totalCollateral the total power of the NFT * @return totalDebt the total debt of the NFT * @return availableBorrows the borrowing power left of the NFT * @return healthFactor the current health factor of the NFT **/ function getNftDebtData(address nftAsset, uint256 nftTokenId) external view returns ( uint256 loanId, address reserveAsset, uint256 totalCollateral, uint256 totalDebt, uint256 availableBorrows, uint256 healthFactor ); /** * @dev Returns the auction data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return bidderAddress the highest bidder address of the loan * @return bidPrice the highest bid price in Reserve of the loan * @return bidBorrowAmount the borrow amount in Reserve of the loan * @return bidFine the penalty fine of the loan **/ function getNftAuctionData(address nftAsset, uint256 nftTokenId) external view returns ( uint256 loanId, address bidderAddress, uint256 bidPrice, uint256 bidBorrowAmount, uint256 bidFine ); function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId) external view returns (uint256 liquidatePrice, uint256 paybackAmount); function getNftsList() external view returns (address[] memory); /** * @dev Set the _pause state of a reserve * - Only callable by the LendPool contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external; /** * @dev Returns if the LendPool is paused */ function paused() external view returns (bool); function getAddressesProvider() external view returns (ILendPoolAddressesProvider); function initReserve( address asset, address bTokenAddress, address debtTokenAddress, address interestRateAddress ) external; function initNft(address asset, address bNftAddress) external; function setReserveInterestRateAddress(address asset, address rateAddress) external; function setReserveConfiguration(address asset, uint256 configuration) external; function setNftConfiguration(address asset, uint256 configuration) external; function setMaxNumberOfReserves(uint256 val) external; function setMaxNumberOfNfts(uint256 val) external; function getMaxNumberOfReserves() external view returns (uint256); function getMaxNumberOfNfts() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {DataTypes} from "../libraries/types/DataTypes.sol"; interface ILendPoolLoan { /** * @dev Emitted on initialization to share location of dependent notes * @param pool The address of the associated lend pool */ event Initialized(address indexed pool); /** * @dev Emitted when a loan is created * @param user The address initiating the action */ event LoanCreated( address indexed user, address indexed onBehalfOf, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amount, uint256 borrowIndex ); /** * @dev Emitted when a loan is updated * @param user The address initiating the action */ event LoanUpdated( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amountAdded, uint256 amountTaken, uint256 borrowIndex ); /** * @dev Emitted when a loan is repaid by the borrower * @param user The address initiating the action */ event LoanRepaid( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amount, uint256 borrowIndex ); /** * @dev Emitted when a loan is auction by the liquidator * @param user The address initiating the action */ event LoanAuctioned( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, uint256 amount, uint256 borrowIndex, address bidder, uint256 price, address previousBidder, uint256 previousPrice ); /** * @dev Emitted when a loan is redeemed * @param user The address initiating the action */ event LoanRedeemed( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amountTaken, uint256 borrowIndex ); /** * @dev Emitted when a loan is liquidate by the liquidator * @param user The address initiating the action */ event LoanLiquidated( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amount, uint256 borrowIndex ); function initNft(address nftAsset, address bNftAddress) external; /** * @dev Create store a loan object with some params * @param initiator The address of the user initiating the borrow * @param onBehalfOf The address receiving the loan */ function createLoan( address initiator, address onBehalfOf, address nftAsset, uint256 nftTokenId, address bNftAddress, address reserveAsset, uint256 amount, uint256 borrowIndex ) external returns (uint256); /** * @dev Update the given loan with some params * * Requirements: * - The caller must be a holder of the loan * - The loan must be in state Active * @param initiator The address of the user initiating the borrow */ function updateLoan( address initiator, uint256 loanId, uint256 amountAdded, uint256 amountTaken, uint256 borrowIndex ) external; /** * @dev Repay the given loan * * Requirements: * - The caller must be a holder of the loan * - The caller must send in principal + interest * - The loan must be in state Active * * @param initiator The address of the user initiating the repay * @param loanId The loan getting burned * @param bNftAddress The address of bNFT */ function repayLoan( address initiator, uint256 loanId, address bNftAddress, uint256 amount, uint256 borrowIndex ) external; /** * @dev Auction the given loan * * Requirements: * - The price must be greater than current highest price * - The loan must be in state Active or Auction * * @param initiator The address of the user initiating the auction * @param loanId The loan getting auctioned * @param bidPrice The bid price of this auction */ function auctionLoan( address initiator, uint256 loanId, address onBehalfOf, uint256 bidPrice, uint256 borrowAmount, uint256 borrowIndex ) external; /** * @dev Redeem the given loan with some params * * Requirements: * - The caller must be a holder of the loan * - The loan must be in state Auction * @param initiator The address of the user initiating the borrow */ function redeemLoan( address initiator, uint256 loanId, uint256 amountTaken, uint256 borrowIndex ) external; /** * @dev Liquidate the given loan * * Requirements: * - The caller must send in principal + interest * - The loan must be in state Active * * @param initiator The address of the user initiating the auction * @param loanId The loan getting burned * @param bNftAddress The address of bNFT */ function liquidateLoan( address initiator, uint256 loanId, address bNftAddress, uint256 borrowAmount, uint256 borrowIndex ) external; function borrowerOf(uint256 loanId) external view returns (address); function getCollateralLoanId(address nftAsset, uint256 nftTokenId) external view returns (uint256); function getLoan(uint256 loanId) external view returns (DataTypes.LoanData memory loanData); function getLoanCollateralAndReserve(uint256 loanId) external view returns ( address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 scaledAmount ); function getLoanReserveBorrowScaledAmount(uint256 loanId) external view returns (address, uint256); function getLoanReserveBorrowAmount(uint256 loanId) external view returns (address, uint256); function getLoanHighestBid(uint256 loanId) external view returns (address, uint256); function getNftCollateralAmount(address nftAsset) external view returns (uint256); function getUserNftCollateralAmount(address user, address nftAsset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title LendPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Bend Governance * @author Bend **/ interface ILendPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendPoolUpdated(address indexed newAddress, bytes encodedCallData); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendPoolConfiguratorUpdated(address indexed newAddress, bytes encodedCallData); event ReserveOracleUpdated(address indexed newAddress); event NftOracleUpdated(address indexed newAddress); event LendPoolLoanUpdated(address indexed newAddress, bytes encodedCallData); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy, bytes encodedCallData); event BNFTRegistryUpdated(address indexed newAddress); event LendPoolLiquidatorUpdated(address indexed newAddress); event IncentivesControllerUpdated(address indexed newAddress); event UIDataProviderUpdated(address indexed newAddress); event BendDataProviderUpdated(address indexed newAddress); event WalletBalanceProviderUpdated(address indexed newAddress); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy( bytes32 id, address impl, bytes memory encodedCallData ) external; function getAddress(bytes32 id) external view returns (address); function getLendPool() external view returns (address); function setLendPoolImpl(address pool, bytes memory encodedCallData) external; function getLendPoolConfigurator() external view returns (address); function setLendPoolConfiguratorImpl(address configurator, bytes memory encodedCallData) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getReserveOracle() external view returns (address); function setReserveOracle(address reserveOracle) external; function getNFTOracle() external view returns (address); function setNFTOracle(address nftOracle) external; function getLendPoolLoan() external view returns (address); function setLendPoolLoanImpl(address loan, bytes memory encodedCallData) external; function getBNFTRegistry() external view returns (address); function setBNFTRegistry(address factory) external; function getLendPoolLiquidator() external view returns (address); function setLendPoolLiquidator(address liquidator) external; function getIncentivesController() external view returns (address); function setIncentivesController(address controller) external; function getUIDataProvider() external view returns (address); function setUIDataProvider(address provider) external; function getBendDataProvider() external view returns (address); function setBendDataProvider(address provider) external; function getWalletBalanceProvider() external view returns (address); function setWalletBalanceProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @dev Interface for a permittable ERC721 contract * See https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC72 allowance (see {IERC721-allowance}) by * presenting a message signed by the account. By not relying on {IERC721-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IPunks { function balanceOf(address account) external view returns (uint256); function punkIndexToAddress(uint256 punkIndex) external view returns (address owner); function buyPunk(uint256 punkIndex) external; function transferPunk(address to, uint256 punkIndex) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @dev Interface for a permittable ERC721 contract * See https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC72 allowance (see {IERC721-allowance}) by * presenting a message signed by the account. By not relying on {IERC721-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IWrappedPunks is IERC721 { function punkContract() external view returns (address); function mint(uint256 punkIndex) external; function burn(uint256 punkIndex) external; function registerProxy() external; function proxyInfo(address user) external returns (address proxy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IPunkGateway { /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet * and lock collateral asset in contract * @param reserveAsset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param punkIndex The index of the CryptoPunk used as collteral * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function borrow( address reserveAsset, uint256 amount, uint256 punkIndex, address onBehalfOf, uint16 referralCode ) external; /** * @notice Repays a borrowed `amount` on a specific punk, burning the equivalent loan owned * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param punkIndex The index of the CryptoPunk used as collteral * @param amount The amount to repay * @return The final amount repaid, loan is burned or not **/ function repay(uint256 punkIndex, uint256 amount) external returns (uint256, bool); /** * @notice auction a unhealth punk loan with ERC20 reserve * @param punkIndex The index of the CryptoPunk used as collteral * @param bidPrice The bid price **/ function auction( uint256 punkIndex, uint256 bidPrice, address onBehalfOf ) external; /** * @notice redeem a unhealth punk loan with ERC20 reserve * @param punkIndex The index of the CryptoPunk used as collteral * @param amount The amount to repay the debt and bid fine **/ function redeem(uint256 punkIndex, uint256 amount) external returns (uint256); /** * @notice liquidate a unhealth punk loan with ERC20 reserve * @param punkIndex The index of the CryptoPunk used as collteral **/ function liquidate(uint256 punkIndex, uint256 amount) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral * - E.g. User borrows 100 ETH, receiving the 100 ETH in his wallet * and lock collateral asset in contract * @param amount The amount to be borrowed * @param punkIndex The index of the CryptoPunk to deposit * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function borrowETH( uint256 amount, uint256 punkIndex, address onBehalfOf, uint16 referralCode ) external; /** * @notice Repays a borrowed `amount` on a specific punk with native ETH * - E.g. User repays 100 ETH, burning loan and receives collateral asset * @param punkIndex The index of the CryptoPunk to repay * @param amount The amount to repay * @return The final amount repaid, loan is burned or not **/ function repayETH(uint256 punkIndex, uint256 amount) external payable returns (uint256, bool); /** * @notice auction a unhealth punk loan with native ETH * @param punkIndex The index of the CryptoPunk to repay * @param onBehalfOf Address of the user who will receive the CryptoPunk. Should be the address of the user itself * calling the function if he wants to get collateral **/ function auctionETH(uint256 punkIndex, address onBehalfOf) external payable; /** * @notice liquidate a unhealth punk loan with native ETH * @param punkIndex The index of the CryptoPunk to repay * @param amount The amount to repay the debt and bid fine **/ function redeemETH(uint256 punkIndex, uint256 amount) external payable returns (uint256); /** * @notice liquidate a unhealth punk loan with native ETH * @param punkIndex The index of the CryptoPunk to repay **/ function liquidateETH(uint256 punkIndex) external payable returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; library DataTypes { struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address bTokenAddress; address debtTokenAddress; //address of the interest rate strategy address interestRateAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct NftData { //stores the nft configuration NftConfigurationMap configuration; //address of the bNFT contract address bNftAddress; //the id of the nft. Represents the position in the list of the active nfts uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct NftConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 56: NFT is active //bit 57: NFT is frozen uint256 data; } /** * @dev Enum describing the current state of a loan * State change flow: * Created -> Active -> Repaid * -> Auction -> Defaulted */ enum LoanState { // We need a default that is not 'Created' - this is the zero value None, // The loan data is stored, but not initiated yet. Created, // The loan has been initialized, funds have been delivered to the borrower and the collateral is held. Active, // The loan is in auction, higest price liquidator will got chance to claim it. Auction, // The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state. Repaid, // The loan was delinquent and collateral claimed by the liquidator. This is a terminal state. Defaulted } struct LoanData { //the id of the nft loan uint256 loanId; //the current state of the loan LoanState state; //address of borrower address borrower; //address of nft asset token address nftAsset; //the id of nft token uint256 nftTokenId; //address of reserve asset token address reserveAsset; //scaled borrow amount. Expressed in ray uint256 scaledAmount; //start time of first bid time uint256 bidStartTimestamp; //bidder address of higest bid address bidderAddress; //price of higest bid uint256 bidPrice; //borrow amount of loan uint256 bidBorrowAmount; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IWETHGateway { /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (bTokens) * is minted. * @param onBehalfOf address of the user who will receive the bTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH(address onBehalfOf, uint16 referralCode) external payable; /** * @dev withdraws the WETH _reserves of msg.sender. * @param amount amount of bWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH(uint256 amount, address to) external; /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendPool.borrow`. * @param amount the amount of ETH to borrow * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( uint256 amount, address nftAsset, uint256 nftTokenId, address onBehalfOf, uint16 referralCode ) external; /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything */ function repayETH( address nftAsset, uint256 nftTokenId, uint256 amount ) external payable returns (uint256, bool); /** * @dev auction a borrow on the WETH reserve * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param onBehalfOf Address of the user who will receive the underlying NFT used as collateral. * Should be the address of the borrower itself calling the function if he wants to borrow against his own collateral. */ function auctionETH( address nftAsset, uint256 nftTokenId, address onBehalfOf ) external payable; /** * @dev redeems a borrow on the WETH reserve * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay the debt and bid fine */ function redeemETH( address nftAsset, uint256 nftTokenId, uint256 amount ) external payable returns (uint256); /** * @dev liquidates a borrow on the WETH reserve * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral */ function liquidateETH(address nftAsset, uint256 nftTokenId) external payable returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import {IPunks} from "../interfaces/IPunks.sol"; /** * @title EmergencyTokenRecovery * @notice Add Emergency Recovery Logic to contract implementation * @author Bend **/ abstract contract EmergencyTokenRecoveryUpgradeable is OwnableUpgradeable { event EmergencyEtherTransfer(address indexed to, uint256 amount); function __EmergencyTokenRecovery_init() internal onlyInitializing { __Ownable_init(); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyERC20Transfer( address token, address to, uint256 amount ) external onlyOwner { IERC20Upgradeable(token).transfer(to, amount); } /** * @dev transfer ERC721 from the utility contract, for ERC721 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param id token id to send */ function emergencyERC721Transfer( address token, address to, uint256 id ) external onlyOwner { IERC721Upgradeable(token).safeTransferFrom(address(this), to, id); } /** * @dev transfer CryptoPunks from the utility contract, for punks recovery in case of stuck punks * due direct transfers to the contract address. * @param to recipient of the transfer * @param index punk index to send */ function emergencyPunksTransfer( address punks, address to, uint256 index ) external onlyOwner { IPunks(punks).transferPunk(to, index); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { (bool success, ) = to.call{value: amount}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); emit EmergencyEtherTransfer(to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due direct transfers to the contract address. token token to transfer to recipient of the transfer amount amount to send/
function emergencyERC20Transfer( address token, address to, uint256 amount ) external onlyOwner { IERC20Upgradeable(token).transfer(to, amount); }
12,045,213
/** ██████╗░░█████╗░███╗░░██╗████████╗██╗░░██╗███████╗░█████╗░███╗░░██╗ ██╔══██╗██╔══██╗████╗░██║╚══██╔══╝██║░░██║██╔════╝██╔══██╗████╗░██║ ██████╔╝███████║██╔██╗██║░░░██║░░░███████║█████╗░░██║░░██║██╔██╗██║ ██╔═══╝░██╔══██║██║╚████║░░░██║░░░██╔══██║██╔══╝░░██║░░██║██║╚████║ ██║░░░░░██║░░██║██║░╚███║░░░██║░░░██║░░██║███████╗╚█████╔╝██║░╚███║ ╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚══════╝░╚════╝░╚═╝░░╚══╝ ██████╗░██╗░░░██╗░██████╗██╗███╗░░██╗███████╗░██████╗░██████╗  ░█████╗░██╗░░░░░██╗░░░██╗██████╗░ ██╔══██╗██║░░░██║██╔════╝██║████╗░██║██╔════╝██╔════╝██╔════╝  ██╔══██╗██║░░░░░██║░░░██║██╔══██╗ ██████╦╝██║░░░██║╚█████╗░██║██╔██╗██║█████╗░░╚█████╗░╚█████╗░  ██║░░╚═╝██║░░░░░██║░░░██║██████╦╝ ██╔══██╗██║░░░██║░╚═══██╗██║██║╚████║██╔══╝░░░╚═══██╗░╚═══██╗  ██║░░██╗██║░░░░░██║░░░██║██╔══██╗ ██████╦╝╚██████╔╝██████╔╝██║██║░╚███║███████╗██████╔╝██████╔╝  ╚█████╔╝███████╗╚██████╔╝██████╦╝ ╚═════╝░░╚═════╝░╚═════╝░╚═╝╚═╝░░╚══╝╚══════╝╚═════╝░╚═════╝░  ░╚════╝░╚══════╝░╚═════╝░╚═════╝░ */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableMap.sol) pragma solidity ^0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI = ""; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Fonction to lock the sale of the NFT bool public isSecondaryMarketOpen = false; mapping(address => bool) public whitelistTransfer; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } // Fonction to lock the sale of the NFT or to unlock function _changeSecondaryMarketState() internal virtual { isSecondaryMarketOpen = !isSecondaryMarketOpen; } // Fonction add or remove address from transfer Whitelist function _modifyAuthorizedSellers(address[] memory addresses, bool state) internal virtual { for (uint256 i = 0; i < addresses.length; i++) { whitelistTransfer[addresses[i]] = state; } } // View Function to check if an adress is present on the map whiteListTransfer function _isWhitelistTransfer(address addr) internal view virtual returns (bool) { return whitelistTransfer[addr]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI_ = baseURI(); return bytes(baseURI_).length > 0 ? string(abi.encodePacked(baseURI_, tokenId.toString())) : ""; } function baseURI() public view virtual returns (string memory) { return _baseURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); //require(isSecondaryMarketOpen == true, "Secondary Market sale is not open"); if (isSecondaryMarketOpen == false){ require(whitelistTransfer[from], "Transfer is not authorized for the Sender : contact the project team to be on the Whitelist"); } _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Can modify the shares own by the team. * They triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. * After the transfer the new shares are setup */ function _modifyShares(address[] memory oldPayees,address[] memory newPayees , uint256[] memory shares_) internal virtual { // triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals. for (uint256 i = 0; i < oldPayees.length; i++) { require(_shares[oldPayees[i]] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(oldPayees[i], totalReceived, released(oldPayees[i])); if (payment != 0){ _released[oldPayees[i]] += payment; _totalReleased += payment; Address.sendValue(payable(oldPayees[i]), payment); emit PaymentReleased(oldPayees[i], payment); } _released[oldPayees[i]] = 0; _shares[oldPayees[i]] = 0; } // refresh the shares variable to start as a new team shares _totalShares = 0; _totalReleased = 0; // Update des shares for the Payees @dev wants require(newPayees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(newPayees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < newPayees.length; i++) { _addPayee(newPayees[i], shares_[i]); } } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: contracts/PantheonBusinessClub.sol pragma solidity ^0.8.0; /** * @title Panthéon Business Club contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract PantheonBusinessClub is ERC721Enumerable, Ownable, PaymentSplitter { using SafeMath for uint256; // The base price is set here. uint256 public nftPrice = 350000000000000000; // 0.35 ETH // Repartition of ETH earned uint256[] private _teamShares = [16, 16, 12, 36, 20]; address[] public _team = [ 0x17482Fa6221f7A6c8453901711d6E2cb3C1355E7, 0xa2D23B0C857E802B97c99bD006Bd707139bAef9A, 0x645AEe5D605b09350BA2135EB340759357E0fA20, 0x0EefcD4C37C78eD786971EC822a1DA6977B08EaC, 0x0d9A8d33428bB813Ea81D32B57A632C532057Fd5 ]; // Only 20 Pantheon Cards can be purchased per transaction. uint256 public constant maxNumPurchase = 20; // Only 8888 total member card will be generated uint256 public MAX_TOKENS = 8888; // Number of token allowed for the Presale uint256 public totalEarlyAccessTokensAllowed = 500; // List of address whitelisted for the Presale mapping(address => bool) private earlyAccessAllowList; // Number max allow during stages uint256 public stage = 0; uint256 private stage2 = 2222; uint256 private stage3 = 3333; uint256 private stage4 = 4444; uint256 private stage5 = 5555; uint256 private stage6 = 6666; uint256 private stage7 = 7777; // List of addresse allowed for different stages mapping(address => bool) private whitelistStage2; mapping(address => bool) private whitelistStage3; mapping(address => bool) private whitelistStage4; mapping(address => bool) private whitelistStage5; mapping(address => bool) private whitelistStage6; mapping(address => bool) private whitelistStage7; // Burn variable true or false if you want people to be able to burn tokens bool public isBurnEnabled = false; event ChangeBurnState(bool _isBurnEnabled); //The hash of the concatented hash string of all the images. string public provenance = ''; /** * The state of the sale: * 0 = closed * 1 = EA * 2 = WL2, 3 = WL3, 4 = WL4, 5 = WL5, 6 = WL6, 7 = WL7 * 8 = stage * 9 = open */ uint256 public saleState = 0; constructor() ERC721("PantheonBusinessClub", "PBC") PaymentSplitter(_team, _teamShares) { setBaseURI('ipfs://QmaWqGvPUVeBRfEc39RRqZ9Hm91kx4qfZiFgGS6TgPbEe7/'); _safeMint(msg.sender, totalSupply()); } /** * Set URL of the NFT */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /** * Modify Shares in paymentSplitter */ function modifyShares(uint256[] memory shares_) public onlyOwner { _modifyShares(_team, _team, shares_); } /** * Modify Shares and Team addresses in paymentSplitter */ function modifyTeamAndShares(address[] memory oldPayees,address[] memory newPayees , uint256[] memory shares_) public onlyOwner { _modifyShares(oldPayees, newPayees, shares_); _team = newPayees; } /** * Lock or unlock the transfer of tokens */ function changeSecondaryMarketState() public onlyOwner { _changeSecondaryMarketState(); } /** * Modify authorized transfer whitelist */ function modifyAuthorizedSellers(address[] memory addresses, bool state) public onlyOwner { _modifyAuthorizedSellers(addresses, state); } /** * retrait des eth stockés dans le smart contrat par le contract Owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * Set some tokens aside. */ function reserveTokens(uint256 number) public onlyOwner { require( totalSupply().add(number) <= MAX_TOKENS, 'Reservation would exceed max supply' ); uint256 i; for (i = 0; i < number; i++) { _safeMint(msg.sender, totalSupply() + i); } } /** * Ability for people to burn their tokens */ function burn(uint256 tokenId) external { require(isBurnEnabled, "Pantheon: burning disabled"); require( _isApprovedOrOwner(msg.sender, tokenId), "Pantheon: burn caller is not owner" ); _burn(tokenId); totalSupply().sub(1); } /** * Ability for people to burn their tokens */ function burnRemainingTokens(uint256 tokenNb) external onlyOwner { require(MAX_TOKENS - tokenNb >= totalSupply(), 'Invalid state'); MAX_TOKENS = MAX_TOKENS - tokenNb; } /** * Set the state of the sale. */ function setSaleState(uint256 newState) public onlyOwner { require(newState >= 0 && newState <= 9, 'Invalid state'); saleState = newState; } function setProvenanceHash(string memory hash) public onlyOwner { provenance = hash; } function setPrice(uint256 value) public onlyOwner { nftPrice = value; } function setStage(uint256 value) public onlyOwner { stage = value; } function setBurnState(bool _isBurnEnabled) external onlyOwner { isBurnEnabled = _isBurnEnabled; emit ChangeBurnState(_isBurnEnabled); } /** * Early Access Member list for the presale */ function changeEarlyAccessMembers(address[] memory addresses, bool state) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { earlyAccessAllowList[addresses[i]] = state; } } /** * Allow users to remove themselves from the whitelist */ function removeEarlyAccessMemberHimself() public { require( earlyAccessAllowList[msg.sender], 'Sender is not on the early access list' ); earlyAccessAllowList[msg.sender] = false; } function isWhitelistTransfer(address addr) public view returns (bool) { return _isWhitelistTransfer(addr); } /** * Whitelist functions for stages */ function changeWhitelistMembersForStage(address[] memory addresses, uint256 stageNumber, bool state) public onlyOwner { if (stageNumber == 2) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage2[addresses[i]] = state; } } else if (stageNumber == 3) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage3[addresses[i]] = state; } } else if (stageNumber == 4) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage4[addresses[i]] = state; } } else if (stageNumber == 5) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage5[addresses[i]] = state; } } else if (stageNumber == 6) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage6[addresses[i]] = state; } } else if (stageNumber == 7) { for (uint256 i = 0; i < addresses.length; i++) { whitelistStage7[addresses[i]] = state; } } } function isWhitelistForStage(address addr, uint256 stageNumber) public view returns (bool) { if (stageNumber == 2) { return whitelistStage2[addr]; } else if (stageNumber == 3) { return whitelistStage3[addr]; } else if (stageNumber == 4) { return whitelistStage4[addr]; } else if (stageNumber == 5) { return whitelistStage5[addr]; } else if (stageNumber == 6) { return whitelistStage6[addr]; } else if (stageNumber == 7) { return whitelistStage7[addr]; } } function _checkEarlyAccess(address sender, uint256 numberOfTokens) internal view { uint256 supply = totalSupply(); if (saleState == 1) { require( earlyAccessAllowList[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= totalEarlyAccessTokensAllowed, 'Minting would exceed total allowed for early access' ); } else if (saleState == 2) { require( whitelistStage2[sender], 'Sender is not on the Whitelist' ); require( supply + numberOfTokens <= stage2, 'Minting would exceed total allowed for early access' ); } else if (saleState == 3) { require( whitelistStage3[sender], 'Sender is not on the Whitelist' ); require( supply + numberOfTokens <= stage3, 'Minting would exceed total allowed for early access' ); } else if (saleState == 4) { require( whitelistStage4[sender], 'Sender is not on the Whitelist' ); require( supply + numberOfTokens <= stage4, 'Minting would exceed total allowed for early access' ); } else if (saleState == 5) { require( whitelistStage5[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= stage5, 'Minting would exceed total allowed for early access' ); } else if (saleState == 6) { require( whitelistStage6[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= stage6, 'Minting would exceed total allowed for early access' ); } else if (saleState == 7) { require( whitelistStage7[sender], 'Sender is not on the early access list' ); require( supply + numberOfTokens <= stage7, 'Minting would exceed total allowed for early access' ); } } /** * Verify if we are on the whitelist or not */ function checkIfWhitelist(address addr) public view returns (bool) { return earlyAccessAllowList[addr]; } /** * Number of token max you can mint with 1 transaction * You can make unlimmited number of transactions */ function _checkNumberOfTokens(uint256 numberOfTokens) internal pure { require( numberOfTokens <= maxNumPurchase, 'Can only mint 20 tokens at a time' ); } /** * Mints an NFT */ function mintPBC(uint256 numberOfTokens) public payable { require( saleState == 1 || saleState == 2 || saleState == 3 || saleState == 4 || saleState == 5 || saleState == 6 || saleState == 7 || saleState == 8 || saleState == 9, 'Sale must be active to mint' ); if (saleState == 1 || saleState == 2 || saleState == 3 || saleState == 4 || saleState == 5 || saleState == 6 || saleState == 7) { _checkEarlyAccess(msg.sender, numberOfTokens); _checkNumberOfTokens(numberOfTokens); } else if (saleState == 8) { _checkNumberOfTokens(numberOfTokens); require( totalSupply().add(numberOfTokens) <= stage, 'Purchase would exceed stage supply, confirm with the project team the maximum card available for this stage' ); } else if (saleState == 9) { _checkNumberOfTokens(numberOfTokens); } require( totalSupply().add(numberOfTokens) <= MAX_TOKENS, 'Purchase would exceed max supply' ); require( nftPrice.mul(numberOfTokens) <= msg.value, 'Ether value sent is not correct' ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } /** * Mint on wallet list */ function mintG(address[] memory addresses, uint256 nbCard) public onlyOwner { require( totalSupply().add(addresses.length * nbCard) <= MAX_TOKENS, 'Reservation would exceed max supply' ); uint256 i; for (i = 0; i < addresses.length; i++) { uint256 j; for (j = 0; j < nbCard; j++) { uint256 mintIndex = totalSupply(); _safeMint(addresses[i], mintIndex); } } } }
Set the state of the sale./
function setSaleState(uint256 newState) public onlyOwner { require(newState >= 0 && newState <= 9, 'Invalid state'); saleState = newState; }
6,127,379
pragma solidity ^0.4.19; /** *This is the PoWH3D code but Norsefire but his dick in it. * Defapabitch (me) has unfucked the mistakes Norsefire did, which was to put dumb fucking comments here. * Defapabitch, student. **/ contract Defapacoin { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); event Approval( address indexed owner, address indexed spender, uint256 value ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Defapacoin"; string public symbol = "Defap"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 100 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 1 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function Defapacoin() public { } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * NEW AND IMPROVED ZERO FEE ON TRANSFER BECAUSE FUCK EXTORTION */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // fire event transferFrom(_customerAddress, _toAddress, 0); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*================================= = HURR-DURR = =================================*/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // Check for approved spend if (_from != msg.sender) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; } require(_to != address(0)); require(_value <= tokenBalanceLedger_[_from]); // Move the tokens across tokenBalanceLedger_[_from] = tokenBalanceLedger_[_from] - _value; tokenBalanceLedger_[_to] = tokenBalanceLedger_[_to] + _value; // Fire 20 event Transfer(_from, _to, _value); // All's well that ends well return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
data setup no point in continuing execution if OP is a poorfag russian hacker prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world (or hackers) and yes we know that the safemath function automatically rules out the "greater then" equasion. is the user referred by a masternode? is this a referred purchase? no cheating! does the referrer have at least X whole tokens? i.e is the referrer a godly chad masternode wealth redistribution no ref purchase add the referral bonus back to the global dividends cake we can't give people infinite ethereum add tokens to the pool take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder calculate the amount of tokens the customer receives over his purchase add tokens to the pool
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if(tokenSupply_ > 0){ tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); tokenSupply_ = _amountOfTokens; } payoutsTo_[_customerAddress] += _updatedPayouts; return _amountOfTokens; }
201,957
./partial_match/3/0xD5e2A366f9Df8d3772B0b8A0AafeCB0F03fD77B3/sources/DemoToken.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rewardThisBlock = getRewardPerBlock(block.number); uint256 DemoReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint); Demo.mint(address(this), DemoReward); pool.accDemoPerShare = pool.accDemoPerShare.add(DemoReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
5,185,256
./full_match/80001/0xA875F95e4B5BAFC9C16B3c8267B429901905B9a4/sources/src/InfiniPack.sol
Override the burn function to take a GenericRequest and a signature Make a generic request from the Burn Request
function burnWithSignature(GenericRequest calldata _req, bytes calldata _signature) external returns (address signer) { signer = _processRequest(_req, _signature); (address from, uint256 id, uint256 amount) = extractBurnData(_req); _burn(from, id, amount); return signer; }
9,523,652
pragma solidity ^0.4.21; contract Owner { address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } function Owner(address _owner) public { owner = _owner; } function changeOwner(address _newOwnerAddr) public onlyOwner { require(_newOwnerAddr != address(0)); owner = _newOwnerAddr; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Extradecoin is Owner { using SafeMath for uint256; string public constant name = "EXTRADECOIN"; string public constant symbol = "ETE"; uint public constant decimals = 18; uint256 constant public totalSupply = 250000000 * 10 ** 18; // 250 mil tokens will be supplied mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; address public adminAddress; address public walletAddress; address public founderAddress; address public advisorAddress; mapping(address => uint256) public totalInvestedAmountOf; uint constant lockPeriod1 = 3 years; // 1st locked period for tokens allocation of founder and team uint constant lockPeriod2 = 1 years; // 2nd locked period for tokens allocation of founder and team uint constant lockPeriod3 = 90 days; // 3nd locked period for tokens allocation of advisor and ICO partners uint constant NOT_SALE = 0; // Not in sales uint constant IN_ICO = 1; // In ICO uint constant END_SALE = 2; // End sales uint256 public constant salesAllocation = 125000000 * 10 ** 18; // 125 mil tokens allocated for sales uint256 public constant founderAllocation = 37500000 * 10 ** 18; // 37.5 mil tokens allocated for founders uint256 public constant advisorAllocation = 25000000 * 10 ** 18; // 25 mil tokens allocated for allocated for ICO partners and bonus fund uint256 public constant reservedAllocation = 62500000 * 10 ** 18; // 62.5 mil tokens allocated for reserved, bounty campaigns, ICO partners, and bonus fund uint256 public constant minInvestedCap = 6000 * 10 ** 18; // 2500 ether for softcap uint256 public constant minInvestedAmount = 0.1 * 10 ** 18; // 0.1 ether for mininum ether contribution per transaction uint saleState; uint256 totalInvestedAmount; uint public icoStartTime; uint public icoEndTime; bool public inActive; bool public isSelling; bool public isTransferable; uint public founderAllocatedTime = 1; uint public advisorAllocatedTime = 1; uint256 public icoStandardPrice; uint256 public totalRemainingTokensForSales; // Total tokens remaining for sales uint256 public totalAdvisor; // Total tokens allocated for advisor uint256 public totalReservedTokenAllocation; // Total tokens allocated for reserved event Approval(address indexed owner, address indexed spender, uint256 value); // ERC20 standard event event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 standard event event StartICO(uint state); // Start ICO sales event EndICO(uint state); // End ICO sales event SetICOPrice(uint256 price); // Set ICO standard price event IssueTokens(address investorAddress, uint256 amount, uint256 tokenAmount, uint state); // Issue tokens to investor event AllocateTokensForFounder(address founderAddress, uint256 founderAllocatedTime, uint256 tokenAmount); // Allocate tokens to founders' address event AllocateTokensForAdvisor(address advisorAddress, uint256 advisorAllocatedTime, uint256 tokenAmount); // Allocate tokens to advisor address event AllocateReservedTokens(address reservedAddress, uint256 tokenAmount); // Allocate reserved tokens event AllocateSalesTokens(address salesAllocation, uint256 tokenAmount); // Allocate sales tokens modifier isActive() { require(inActive == false); _; } modifier isInSale() { require(isSelling == true); _; } modifier transferable() { require(isTransferable == true); _; } modifier onlyOwnerOrAdminOrPortal() { require(msg.sender == owner || msg.sender == adminAddress); _; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == adminAddress); _; } function Extradecoin(address _walletAddr, address _adminAddr) public Owner(msg.sender) { require(_walletAddr != address(0)); require(_adminAddr != address(0)); walletAddress = _walletAddr; adminAddress = _adminAddr; inActive = true; totalInvestedAmount = 0; totalRemainingTokensForSales = salesAllocation; totalAdvisor = advisorAllocation; totalReservedTokenAllocation = reservedAllocation; } // Fallback function for token purchasing function () external payable isActive isInSale { uint state = getCurrentState(); require(state == IN_ICO); require(msg.value >= minInvestedAmount); if (state == IN_ICO) { return issueTokensForICO(state); } revert(); } // ERC20 standard function function transfer(address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ERC20 standard function function transferFrom(address _from, address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_from != address(0)); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // ERC20 standard function function approve(address _spender, uint256 _value) external transferable returns (bool) { require(_spender != address(0)); require(_value > 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // Start ICO function startICO() external isActive onlyOwnerOrAdmin returns (bool) { saleState = IN_ICO; icoStartTime = now; isSelling = true; emit StartICO(saleState); return true; } // End ICO function endICO() external isActive onlyOwnerOrAdmin returns (bool) { require(icoEndTime == 0); saleState = END_SALE; isSelling = false; icoEndTime = now; emit EndICO(saleState); return true; } // Set ICO price including ICO standard price, ICO 1st round price, ICO 2nd round price function setICOPrice(uint256 _tokenPerEther) external onlyOwnerOrAdmin returns(bool) { require(_tokenPerEther > 0); icoStandardPrice = _tokenPerEther; emit SetICOPrice(icoStandardPrice); return true; } // Activate token sale function function activate() external onlyOwner { inActive = false; } // Deacivate token sale function function deActivate() external onlyOwner { inActive = true; } // Enable transfer feature of tokens function enableTokenTransfer() external isActive onlyOwner { isTransferable = true; } // Modify wallet function changeWallet(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(walletAddress != _newAddress); walletAddress = _newAddress; } // Modify admin function changeAdminAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(adminAddress != _newAddress); adminAddress = _newAddress; } // Modify founder address to receive founder tokens allocation function changeFounderAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(founderAddress != _newAddress); founderAddress = _newAddress; } // Modify team address to receive team tokens allocation function changeTeamAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(advisorAddress != _newAddress); advisorAddress = _newAddress; } // Allocate tokens for founder vested gradually for 4 year function allocateTokensForFounder() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(founderAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { require(now >= icoEndTime + lockPeriod1); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (founderAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 3; return; } revert(); } // Allocate tokens for advisor and angel investors vested gradually for 1 year function allocateTokensForAdvisor() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(advisorAddress != address(0)); uint256 amount; if (advisorAllocatedTime == 1) { amount = advisorAllocation * 50/100; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForFounder(advisorAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (advisorAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 3; return; } if (advisorAllocatedTime == 3) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 4; return; } if (advisorAllocatedTime == 4) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 5; return; } if (advisorAllocatedTime == 5) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 6; return; } revert(); } // Allocate reserved tokens function allocateReservedTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalReservedTokenAllocation = totalReservedTokenAllocation.sub(_amount); emit AllocateReservedTokens(_addr, _amount); } // Allocate sales tokens function allocateSalesTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalRemainingTokensForSales = totalRemainingTokensForSales.sub(_amount); emit AllocateSalesTokens(_addr, _amount); } // ERC20 standard function function allowance(address _owner, address _spender) external constant returns (uint256) { return allowed[_owner][_spender]; } // Issue tokens to normal investors through ICO rounds function issueTokensForICO(uint _state) private { uint256 price = icoStandardPrice; issueTokens(price, _state); } // Issue tokens to investors and transfer ether to wallet function issueTokens(uint256 _price, uint _state) private { require(walletAddress != address(0)); uint tokenAmount = msg.value.mul(_price).mul(10**18).div(1 ether); totalInvestedAmount = totalInvestedAmount.add(msg.value); walletAddress.transfer(msg.value); emit IssueTokens(msg.sender, msg.value, tokenAmount, _state); } // ERC20 standard function function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } // Get current sales state function getCurrentState() public view returns(uint256) { return saleState; } // Get softcap reaching status function isSoftCapReached() public view returns (bool) { return totalInvestedAmount >= minInvestedCap; } }
Issue tokens to investors and transfer ether to wallet
function issueTokens(uint256 _price, uint _state) private { require(walletAddress != address(0)); uint tokenAmount = msg.value.mul(_price).mul(10**18).div(1 ether); totalInvestedAmount = totalInvestedAmount.add(msg.value); walletAddress.transfer(msg.value); emit IssueTokens(msg.sender, msg.value, tokenAmount, _state); }
10,439,729
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB684(a, b, "SafeMath: subtraction overflow"); } function SUB684(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV551(a, b, "SafeMath: division by zero"); } function DIV551(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD699(a, b, "SafeMath: modulo by zero"); } function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE986(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL437(target, data, "Address: low-level call failed"); } function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT292(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value)); } function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value)); } function SAFEAPPROVE47(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE520(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value)); } function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN808(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).FUNCTIONCALL437(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IMultiVaultStrategy { function WANT777() external view returns (address); //inject NONSTANDARD NAMING function DEPOSIT294() external; //inject NONSTANDARD NAMING function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING function SKIM294() external; //inject NONSTANDARD NAMING function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING } interface IValueMultiVault { function CAP418() external view returns (uint); //inject NONSTANDARD NAMING function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING function EARN427(address _want) external; //inject NONSTANDARD NAMING function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING } interface IShareConverter { function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING } interface Converter { function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING } contract MultiStablesVaultController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public strategist; struct StrategyInfo { address strategy; uint quota; // set = 0 to disable uint percent; } IValueMultiVault public vault; address public basedWant; address[] public wantTokens; // sorted by preference // want => quota, length mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength; // want => stratId => StrategyInfo mapping(address => mapping(uint => StrategyInfo)) public strategies; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public investDisabled; IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...) address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array constructor(IValueMultiVault _vault) public { require(address(_vault) != address(0), "!_vault"); vault = _vault; basedWant = vault.TOKEN385(); governance = msg.sender; strategist = msg.sender; } function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = true; } function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = false; } function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantQuota[_want] = _quota; } function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantStrategyLength[_want] = _length; } // want => stratId => StrategyInfo function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(approvedStrategies[_want][_strategy], "!approved"); strategies[_want][_sid].strategy = _strategy; strategies[_want][_sid].quota = _quota; strategies[_want][_sid].percent = _percent; } function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); shareConverter = _shareConverter; } function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); investDisabled[_want] = _investDisabled; } function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); delete wantTokens; uint _wlength = _wantTokens.length; for (uint i = 0; i < _wlength; ++i) { wantTokens.push(_wantTokens[i]); } } function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING _strategyCount = 0; uint _wlength = wantTokens.length; for (uint i = 0; i < _wlength; i++) { _strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]); } } function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING return wantTokens.length; } function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING uint _bal = 0; for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) { _bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771()); } return _bal; } function WANT777() external view returns (address) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0)) { return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777(); } uint _wlength = wantTokens.length; if (_wlength > 0) { if (_wlength == 1) { return wantTokens[0]; } for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(_want); if (_bal < wantQuota[_want]) { return _want; } } } return basedWant; } function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); lazySelectedBestStrategy = _strategy; } function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) { return lazySelectedBestStrategy; } uint _wantStrategyLength = wantStrategyLength[_want]; _strategy = address(0); if (_wantStrategyLength == 0) return _strategy; uint _totalBal = WANTSTRATEGYBALANCE73(_want); if (_totalBal == 0) { // first depositor, simply return the first strategy return strategies[_want][0].strategy; } uint _bestDiff = 201; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771(); if (_stratBal < sinfo.quota) { uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent] if (_diff < _bestDiff) { _bestDiff = _diff; _strategy = sinfo.strategy; } } } if (_strategy == address(0)) { _strategy = strategies[_want][0].strategy; } } function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist"); address _strategy = GETBESTSTRATEGY227(_token); if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) { // forward to vault and then call earnExtra() by its governance IERC20(_token).SAFETRANSFER627(address(vault), _amount); } else { IERC20(_token).SAFETRANSFER627(_strategy, _amount); IMultiVaultStrategy(_strategy).DEPOSIT294(); } } function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING address _strategy = GETBESTSTRATEGY227(_want); return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount); } function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING uint _wlength = wantTokens.length; if (_wlength == 0) { return 0; } _totalBal = 0; for (uint i = 0; i < _wlength; i++) { address wt = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(wt); if (wt != _want) { _bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal); if (_sell) { _bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling } } _totalBal = _totalBal.ADD260(_bal); } } function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); // WithdrawAll sends 'want' to 'vault' IMultiVaultStrategy(_strategy).WITHDRAWALL927(); } function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IERC20(_token).SAFETRANSFER627(address(vault), _amount); } function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IMultiVaultStrategy(_strategy).WITHDRAW808(_token); IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this))); } function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); vault.CLAIMINSURANCE45(); } // note that some strategies do not allow controller to harvest function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).HARVEST506(address(0)); } function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wantStrategyLength = wantStrategyLength[_want]; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wlength = wantTokens.length; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _wantStrategyLength = wantStrategyLength[_want]; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); _srcStrat.WITHDRAWTOCONTROLLER653(_amount); address _srcWant = _srcStrat.WANT777(); address _destWant = _destStrat.WANT777(); if (_srcWant != _destWant) { _amount = IERC20(_srcWant).BALANCEOF771(address(this)); require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0"); IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount); shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount); } IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this))); _destStrat.DEPOSIT294(); } function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING require(msg.sender == address(vault), "!vault"); _withdrawFee = 0; uint _toWithdraw = _amount; uint _wantStrategyLength = wantStrategyLength[_want]; uint _received; for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_want][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); if (_toWithdraw < _stratBal) { _received = _strategy.WITHDRAW808(_toWithdraw); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); return _withdrawFee; } _received = _strategy.WITHDRAWALL927(); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); if (_received >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_received); } if (_toWithdraw > 0) { // still not enough, try to withdraw from other wants strategies uint _wlength = wantTokens.length; for (uint i = _wlength; i > 0; i--) { address wt = wantTokens[i - 1]; if (wt != _want) { (uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw); _withdrawFee = _withdrawFee.ADD260(_wdfee); if (_wamt >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_wamt); } } } return _withdrawFee; } function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING // Check balance uint b = IERC20(_want).BALANCEOF771(address(this)); _withdrawFee = 0; if (b >= _amount) { _wantAmount = b; } else { uint _toWithdraw = _amount.SUB684(b); uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra uint _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal < _toWithdrawOther) { uint _otherStrategyLength = wantStrategyLength[_other]; for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_other][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); uint _needed = _toWithdrawOther.SUB684(_otherBal); uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal; _strategy.WITHDRAWTOCONTROLLER653(_wdamt); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt)); _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal >= _toWithdrawOther) { break; } } } IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal); shareConverter.CONVERT_SHARES33(_other, _want, _otherBal); _wantAmount = IERC20(_want).BALANCEOF771(address(this)); } IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount); } }
inject NONSTANDARD NAMING
function CONVERT_RATE825(address _input, uint _amount) external view returns (uint);
13,085,361
./full_match/100/0x5fD704F0122DAecB9c0f1a00efa1058B326DD4c5/sources/incentives-controller/contracts/incentives/DistributionManager.sol
Configure the assets for a specific emission assetsConfigInput The array of each asset configuration/
function _configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) internal { for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].decimals, assetsConfigInput[i].emissionPerSecond ); } }
14,272,605
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; struct RoleData { mapping(address => bool) members; bytes32 adminRole; } library AccessControlEvents { event OwnerSet(address indexed owner); event OwnerTransferred(address indexed owner, address indexed prevOwner); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../storage/roles.sol"; abstract contract int_hasRole_AccessControl_v1 is sto_AccessControl_Roles { function _hasRole(bytes32 role, address account) internal view returns (bool hasRole_) { hasRole_ = accessControlRolesStore().roles[role].members[account]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./has-role.sol"; abstract contract int_requireAuthorization_AccessControl_v1 is int_hasRole_AccessControl_v1 { function _requireAuthorization(bytes32 role, address account) internal view { require(_hasRole(role, account), "AccessControl: unauthorized"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { int_requireAuthorization_AccessControl_v1 } from "../internal/require-authorization.sol"; abstract contract mod_authorized_AccessControl_v1 is int_requireAuthorization_AccessControl_v1 { modifier authorized(bytes32 role, address account) { _requireAuthorization(role, account); _; } } abstract contract mod_authorized_AccessControl is mod_authorized_AccessControl_v1 {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { RoleData } from "../data.sol"; contract sto_AccessControl_Roles { bytes32 internal constant POS = keccak256("teller_protocol.storage.access_control.roles"); struct AccessControlRolesStorage { mapping(bytes32 => RoleData) roles; } function accessControlRolesStore() internal pure returns (AccessControlRolesStorage storage s) { bytes32 position = POS; assembly { s.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IStakeableNFT { function tokenBaseLoanSize(uint256 tokenId) external view returns (uint256); function tokenURIHash(uint256 tokenId) external view returns (string memory); function tokenContributionAsset(uint256 tokenId) external view returns (address); function tokenContributionSize(uint256 tokenId) external view returns (uint256); function tokenContributionMultiplier(uint256 tokenId) external view returns (uint8); } /** * @notice TellerNFTDictionary Version 1.02 * * @notice This contract is used to gather data for TellerV1 NFTs more efficiently. * @notice This contract has data which must be continuously synchronized with the TellerV1 NFT data * * @author [email protected] */ pragma solidity ^0.8.0; // Contracts import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Interfaces import "./IStakeableNFT.sol"; /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ contract TellerNFTDictionary is IStakeableNFT, AccessControlUpgradeable { struct Tier { uint256 baseLoanSize; string[] hashes; address contributionAsset; uint256 contributionSize; uint8 contributionMultiplier; } mapping(uint256 => uint256) public baseLoanSizes; mapping(uint256 => string[]) public hashes; mapping(uint256 => address) public contributionAssets; mapping(uint256 => uint256) public contributionSizes; mapping(uint256 => uint8) public contributionMultipliers; /* Constants */ bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ mapping(uint256 => uint256) public _tokenTierMappingCompressed; bool public _tokenTierMappingCompressedSet; /* Modifiers */ modifier onlyAdmin() { require(hasRole(ADMIN, _msgSender()), "TellerNFTDictionary: not admin"); _; } function initialize(address initialAdmin) public { _setupRole(ADMIN, initialAdmin); _setRoleAdmin(ADMIN, ADMIN); __AccessControl_init(); } /* External Functions */ /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. */ function getTokenTierIndex(uint256 tokenId) public view returns (uint8 index_) { //32 * 8 = 256 - each uint256 holds the data of 32 tokens . 8 bits each. uint256 mappingIndex = tokenId / 32; uint256 compressedRegister = _tokenTierMappingCompressed[mappingIndex]; //use 31 instead of 32 to account for the '0x' in the start. //the '31 -' reverses our bytes order which is necessary uint256 offset = ((31 - (tokenId % 32)) * 8); uint8 tierIndex = uint8((compressedRegister >> offset)); return tierIndex; } function getTierHashes(uint256 tierIndex) external view returns (string[] memory) { return hashes[tierIndex]; } /** * @notice Adds a new Tier to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTier Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTier(uint256 index, Tier memory newTier) external onlyAdmin returns (bool) { baseLoanSizes[index] = newTier.baseLoanSize; hashes[index] = newTier.hashes; contributionAssets[index] = newTier.contributionAsset; contributionSizes[index] = newTier.contributionSize; contributionMultipliers[index] = newTier.contributionMultiplier; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param tiersMapping Information about the new tiers to add. * * Requirements: * - Caller must have the {Admin} role */ function setAllTokenTierMappings(uint256[] memory tiersMapping) public onlyAdmin returns (bool) { require( !_tokenTierMappingCompressedSet, "TellerNFTDictionary: token tier mapping already set" ); for (uint256 i = 0; i < tiersMapping.length; i++) { _tokenTierMappingCompressed[i] = tiersMapping[i]; } _tokenTierMappingCompressedSet = true; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param index the mapping row, each holds data for 32 tokens * @param tierMapping Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierMapping(uint256 index, uint256 tierMapping) public onlyAdmin returns (bool) { _tokenTierMappingCompressed[index] = tierMapping; return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenIds the NFT token Ids for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenIds( uint256[] calldata tokenIds, uint256 tokenTier ) public onlyAdmin returns (bool) { for (uint256 i; i < tokenIds.length; i++) { setTokenTierForTokenId(tokenIds[i], tokenTier); } return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenId the NFT token Id for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenId(uint256 tokenId, uint256 tokenTier) public onlyAdmin returns (bool) { uint256 mappingIndex = tokenId / 32; uint256 existingRegister = _tokenTierMappingCompressed[mappingIndex]; uint256 offset = ((31 - (tokenId % 32)) * 8); uint256 updateMaskShifted = 0x00000000000000000000000000000000000000000000000000000000000000FF << offset; uint256 updateMaskShiftedNegated = ~updateMaskShifted; uint256 tokenTierShifted = ((0x0000000000000000000000000000000000000000000000000000000000000000 | tokenTier) << offset); uint256 existingRegisterClearedWithMask = existingRegister & updateMaskShiftedNegated; uint256 updatedRegister = existingRegisterClearedWithMask | tokenTierShifted; _tokenTierMappingCompressed[mappingIndex] = updatedRegister; return true; } function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return interfaceId == type(IStakeableNFT).interfaceId || AccessControlUpgradeable.supportsInterface(interfaceId); } /** New methods for the dictionary */ /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return baseLoanSizes[tokenTier]; } /** * @notice It returns Token URI Hash for a token ID. * @param tokenId ID of the token to get info. */ function tokenURIHash(uint256 tokenId) public view override returns (string memory) { uint8 tokenTier = getTokenTierIndex(tokenId); string[] memory tierImageHashes = hashes[tokenTier]; return tierImageHashes[tokenId % (tierImageHashes.length)]; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view override returns (address) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionAssets[tokenTier]; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionSizes[tokenTier]; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view override returns (uint8) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionMultipliers[tokenTier]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { ERC1155Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Libraries import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /*****************************************************************************************************/ /** WARNING **/ /** THIS CONTRACT IS UPGRADEABLE! **/ /** --------------------------------------------------------------------------------------------- **/ /** Do NOT change the order of or PREPEND any storage variables to this or new versions of this **/ /** contract as this will cause the the storage slots to be overwritten on the proxy contract!! **/ /** **/ /** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/ /** more information. **/ /*****************************************************************************************************/ /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ abstract contract TellerNFT_V2 is ERC1155Upgradeable, AccessControlUpgradeable { using EnumerableSet for EnumerableSet.UintSet; /* Constants */ string public constant name = "Teller NFT"; string public constant symbol = "TNFT"; uint256 private constant ID_PADDING = 10000; bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ struct Tier { uint256 baseLoanSize; address contributionAsset; uint256 contributionSize; uint16 contributionMultiplier; } // It holds the total number of tokens in existence. uint256 public totalSupply; // It holds the information about a tier. mapping(uint256 => Tier) public tiers; // It holds the total number of tiers. uint128 public tierCount; // It holds how many tokens types exists in a tier. mapping(uint128 => uint256) public tierTokenCount; // It holds a set of tokenIds for an owner address mapping(address => EnumerableSet.UintSet) internal _ownedTokenIds; // It holds the URI hash containing the token metadata mapping(uint256 => string) internal _idToUriHash; // It is a reverse lookup of the token ID given the metadata hash mapping(string => uint256) internal _uriHashToId; // Hash to the contract metadata string private _contractURIHash; /* Public Functions */ /** * @notice checks if an interface is supported by ITellerNFT or AccessControlUpgradeable * @param interfaceId the identifier of the interface * @return bool stating whether or not our interface is supported */ function supportsInterface(bytes4 interfaceId) public view override(ERC1155Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(super.uri(tokenId), _idToUriHash[tokenId])); } /* External Functions */ /** * @notice The contract metadata URI. * @return the contract URI hash */ function contractURI() external view returns (string memory) { // URI returned from parent just returns base URI return string(abi.encodePacked(super.uri(0), _contractURIHash)); } /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. * @return tierId_ the index of the tier the tokenId belongs to * @return tierTokenId_ the tokenId in tier */ function getTokenTierId(uint256 tokenId) external view returns (uint128 tierId_, uint128 tierTokenId_) { (tierId_, tierTokenId_) = _splitTokenId(tokenId); } /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view returns (uint256) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].baseLoanSize; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view returns (address) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionAsset; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view returns (uint256) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionSize; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view returns (uint16) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionMultiplier; } /** * @notice It returns an array of token IDs owned by an address. * @dev It uses a EnumerableSet to store values and loops over each element to add to the array. * @dev Can be costly if calling within a contract for address with many tokens. * @return owned_ the array of tokenIDs owned by the address */ function getOwnedTokens(address owner) external view returns (uint256[] memory owned_) { EnumerableSet.UintSet storage set = _ownedTokenIds[owner]; owned_ = new uint256[](set.length()); for (uint256 i; i < owned_.length; i++) { owned_[i] = set.at(i); } } /** * @notice Creates new Tiers to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTiers Information about the new tiers to add. * @param tierHashes Metadata hashes belonging to the tiers. * * Requirements: * - Caller must have the {ADMIN} role */ function createTiers( Tier[] calldata newTiers, string[][] calldata tierHashes ) external onlyRole(ADMIN) { require( newTiers.length == tierHashes.length, "Teller: array length mismatch" ); for (uint256 i; i < newTiers.length; i++) { _createTier(newTiers[i], tierHashes[i]); } } /** * @notice creates the tier along with the tier hashes, then saves the tokenId * information in id -> hash and hash -> id mappings * @param newTier the Tier struct containing all the tier information * @param tierHashes the tier hashes to add to the tier */ function _createTier(Tier calldata newTier, string[] calldata tierHashes) internal { // Increment tier counter to use tierCount++; Tier storage tier = tiers[tierCount]; tier.baseLoanSize = newTier.baseLoanSize; tier.contributionAsset = newTier.contributionAsset; tier.contributionSize = newTier.contributionSize; tier.contributionMultiplier = newTier.contributionMultiplier; // Store how many tokens are on the tier tierTokenCount[tierCount] = tierHashes.length; // Set the token URI hash for (uint128 i; i < tierHashes.length; i++) { uint256 tokenId = _mergeTokenId(tierCount, i); _idToUriHash[tokenId] = tierHashes[i]; _uriHashToId[tierHashes[i]] = tokenId; } } /** * @dev See {_setURI}. * * Requirements: * * - `newURI` must be prepended with a forward slash (/) */ function setURI(string memory newURI) external onlyRole(ADMIN) { _setURI(newURI); } /** * @notice Sets the contract level metadata URI hash. * @param contractURIHash The hash to the initial contract level metadata. */ function setContractURIHash(string memory contractURIHash) public onlyRole(ADMIN) { _contractURIHash = contractURIHash; } /** * @notice Initializes the TellerNFT. * @param data Bytes to init the token with. */ function initialize(bytes calldata data) public virtual initializer { // Set the initial URI __ERC1155_init("https://gateway.pinata.cloud/ipfs/"); __AccessControl_init(); // Set admin role for admins _setRoleAdmin(ADMIN, ADMIN); // Set the initial admin _setupRole(ADMIN, _msgSender()); // Set initial contract URI hash setContractURIHash("QmWAfQFFwptzRUCdF2cBFJhcB2gfHJMd7TQt64dZUysk3R"); __TellerNFT_V2_init_unchained(data); } function __TellerNFT_V2_init_unchained(bytes calldata data) internal virtual initializer {} /* Internal Functions */ /** * @notice it removes a token ID from the ownedTokenIds mapping if the balance of * the user's tokenId is 0 * @param account the address to add the token id to * @param id the token ID */ function _removeOwnedTokenCheck(address account, uint256 id) private { if (balanceOf(account, id) == 0) { _ownedTokenIds[account].remove(id); } } /** * @notice it adds a token id to the ownedTokenIds mapping * @param account the address to the add the token ID to * @param id the token ID */ function _addOwnedToken(address account, uint256 id) private { _ownedTokenIds[account].add(id); } /** * @dev Runs super function and then increases total supply. * * See {ERC1155Upgradeable._mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal override { super._mint(account, id, amount, data); // add the id to the owned token ids of the user _addOwnedToken(account, id); totalSupply += amount; } /** * @dev Runs super function and then increases total supply. * * See {ERC1155Upgradeable._mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._mintBatch(to, ids, amounts, data); for (uint256 i; i < amounts.length; i++) { totalSupply += amounts[i]; _addOwnedToken(to, ids[i]); } } /** * @dev Runs super function and then decreases total supply. * * See {ERC1155Upgradeable._burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal override { super._burn(account, id, amount); _removeOwnedTokenCheck(account, id); totalSupply -= amount; } /** * @dev Runs super function and then decreases total supply. * * See {ERC1155Upgradeable._burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal override { super._burnBatch(account, ids, amounts); for (uint256 i; i < amounts.length; i++) { totalSupply -= amounts[i]; _removeOwnedTokenCheck(account, ids[i]); } } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * See {ERC1155Upgradeable._safeTransferFrom}. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal override { super._safeTransferFrom(from, to, id, amount, data); _removeOwnedTokenCheck(from, id); _addOwnedToken(to, id); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * See {ERC1155Upgradeable._safeBatchTransferFrom} */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._safeBatchTransferFrom(from, to, ids, amounts, data); for (uint256 i; i < ids.length; i++) { _removeOwnedTokenCheck(from, ids[i]); _addOwnedToken(to, ids[i]); } } /** * @dev Checks if a token ID exists. To exists the ID must have a URI hash associated. * @param tokenId ID of the token to check. */ function _exists(uint256 tokenId) internal view returns (bool) { return bytes(_idToUriHash[tokenId]).length > 0; } /** * @dev Creates a V2 token ID from a tier ID and tier token ID. * @param tierId Index of the tier to use. * @param tierTokenId ID of the token within the given tier. * @return tokenId_ V2 NFT token ID. */ function _mergeTokenId(uint128 tierId, uint128 tierTokenId) internal pure returns (uint256 tokenId_) { tokenId_ = tierId * ID_PADDING; tokenId_ += tierTokenId; } /** * @dev Creates a V2 token ID from a tier ID and tier token ID. * @param tokenId V2 NFT token ID. * @return tierId_ Index of the token tier. * @return tierTokenId_ ID of the token within the tier. */ function _splitTokenId(uint256 tokenId) internal pure returns (uint128 tierId_, uint128 tierTokenId_) { tierId_ = SafeCast.toUint128(tokenId / ID_PADDING); tierTokenId_ = SafeCast.toUint128(tokenId % ID_PADDING); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; bytes32 constant ADMIN = keccak256("ADMIN"); bytes32 constant MINTER = keccak256("MINTER"); struct MerkleRoot { bytes32 merkleRoot; uint256 tierIndex; } struct ClaimNFTRequest { uint256 merkleIndex; uint256 nodeIndex; uint256 amount; bytes32[] merkleProof; } library DistributorEvents { event Claimed(address indexed account); event MerkleAdded(uint256 index); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import "../store.sol"; import "../../../contexts/access-control/modifiers/authorized.sol"; // Utils import { ADMIN } from "../data.sol"; // Interfaces import "../../mainnet/MainnetTellerNFT.sol"; contract ent_upgradeNFTV2_NFTDistributor_v1 is sto_NFTDistributor, mod_authorized_AccessControl_v1 { /** * @notice Upgrades the reference to the NFT to the V2 deployment address. * @param _nft The address of the TellerNFT. */ function upgradeNFTV2(address _nft) external authorized(ADMIN, msg.sender) { require(distributorStore().version == 0, "Teller: invalid upgrade version"); distributorStore().version = 1; distributorStore().nft = MainnetTellerNFT(_nft); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Interfaces import "../mainnet/MainnetTellerNFT.sol"; // Utils import { MerkleRoot } from "./data.sol"; abstract contract sto_NFTDistributor { struct DistributorStorage { MainnetTellerNFT nft; MerkleRoot[] merkleRoots; mapping(uint256 => mapping(uint256 => uint256)) claimedBitMap; address _dictionary; // DEPRECATED uint256 version; } bytes32 constant POSITION = keccak256("teller_nft.distributor"); function distributorStore() internal pure returns (DistributorStorage storage s) { bytes32 P = POSITION; assembly { s.slot := P } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { TellerNFT_V2 } from "../TellerNFT_V2.sol"; import { TellerNFTDictionary } from "../TellerNFTDictionary.sol"; import { IERC721ReceiverUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; contract MainnetTellerNFT is IERC721ReceiverUpgradeable, TellerNFT_V2 { /* Constants */ address public constant V1 = 0x2ceB85a2402C94305526ab108e7597a102D6C175; TellerNFTDictionary public constant DICT = TellerNFTDictionary(0x72733102AB139FB0367cc29D492c955A7c736079); address public constant diamond = 0xc14D994fe7C5858c93936cc3bD42bb9467d6fB2C; bytes32 public constant MINTER = keccak256("MINTER"); /* Initializers */ /** * @notice Initializes the TellerNFT. * @param data The addresses that should allowed to mint tokens. */ function __TellerNFT_V2_init_unchained(bytes calldata data) internal override initializer { address[] memory minters = abi.decode(data, (address[])); // Set admin role for minters _setRoleAdmin(MINTER, ADMIN); // Set the initial minters for (uint256 i; i < minters.length; i++) { _setupRole(MINTER, minters[i]); } } /* External Functions */ /** * @notice It mints a new token for a Tier index. * @param tierIndex Tier to mint token on. * @param owner The owner of the new token. * * Requirements: * - Caller must be an authorized minter */ function mint( address owner, uint128 tierIndex, uint128 amount ) external onlyRole(MINTER) { // Get the token ID to mint for the user // On a fresh mint, the exact token ID minted is determined on tx execution // with sudo randomness using the block number uint256 tokenId = _mergeTokenId( tierIndex, uint128(block.number % tierTokenCount[tierIndex]) ); _mint(owner, tokenId, uint256(amount), ""); } /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { // Check which 721 token we received // We only care about V1 so we can migrate it if (_msgSender() == V1) { uint256 newTokenId; // if the from address is the diamond address, we trust that we // can decode the data into the newly converted token id if (from == diamond) { newTokenId = abi.decode(data, (uint256)); } else { newTokenId = convertV1TokenId(tokenId); } // Convert V1 token ID and mint 1 new V2 token to the diamond _mint(from, newTokenId, 1, ""); } return IERC721ReceiverUpgradeable.onERC721Received.selector; } /* Public Functions */ /** * @notice it performs a reverse look up on by finding our ID using the * tokenURI hash using the NFT dictionary. Required that the token id exists * @param _tokenId the tokenId to look up */ function convertV1TokenId(uint256 _tokenId) public view returns (uint256 tokenId_) { tokenId_ = _uriHashToId[DICT.tokenURIHash(_tokenId)]; require(_exists(tokenId_), "TellerNFT: invalid token ID"); } }
It returns an array of token IDs owned by an address. It uses a EnumerableSet to store values and loops over each element to add to the array. Can be costly if calling within a contract for address with many tokens. return owned_ the array of tokenIDs owned by the address/
function getOwnedTokens(address owner) external view returns (uint256[] memory owned_) { EnumerableSet.UintSet storage set = _ownedTokenIds[owner]; owned_ = new uint256[](set.length()); for (uint256 i; i < owned_.length; i++) { owned_[i] = set.at(i); } }
6,317,309
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity 0.5.9; import "../Land/erc721/LandBaseToken.sol"; import "../contracts_common/Interfaces/ERC721MandatoryTokenReceiver.sol"; import "../BaseWithStorage/ERC2771Handler.sol"; import "../contracts_common/BaseWithStorage/PausableWithAdmin.sol"; contract LandSwapV2 is ERC721MandatoryTokenReceiver, ERC2771Handler, PausableWithAdmin { bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46; LandBaseToken public _oldLand; LandBaseToken public _newLand; bool internal _initialized; address public _batchMigration; modifier initializer() { require(!_initialized, "LandSwap: Contract already initialized"); _; } function initialize (address admin, address trustedForwarder, address oldLand, address newLand, address batchMigration) public initializer { _admin = admin; __ERC2771Handler_initialize(trustedForwarder); _oldLand = LandBaseToken(oldLand); _newLand = LandBaseToken(newLand); _batchMigration = batchMigration; _initialized = true; } function onERC721BatchReceived(address, address, uint256[] calldata, bytes calldata) external returns (bytes4) { require(msg.sender == address(_oldLand), "NOT_OLD_LAND"); return _ERC721_BATCH_RECEIVED; } function onERC721Received(address, address, uint256, bytes calldata) external returns (bytes4) { require(msg.sender == address(_oldLand), "NOT_OLD_LAND"); return _ERC721_RECEIVED; } function swap(uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data) external whenNotPaused { address from = _msgSender(); _oldLand.batchTransferQuad(from, address(this), sizes, xs, ys, data); for (uint256 i = 0; i < sizes.length; i++) { _newLand.mintQuad(from, sizes[i], xs[i], ys[i], data); } } function migrate(uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data) external whenNotPaused { require(msg.sender == _batchMigration, "LandSwap.migrate: NOT_BATCH_MIGRATION"); address from = _oldLand.ownerOf(xs[0] + ys[0] * 408); for (uint256 index = 0; index < sizes.length; index++) { for (uint256 i = 0; i < sizes[index]; i++) { for (uint256 j = 0; j < sizes[index]; j++) { uint256 x = xs[index] + i; uint256 y = ys[index] + j; uint256 id = x + y * 408; require(from == _oldLand.ownerOf(id), "LandSwap.migrate: NOT_OWNER"); } } } _oldLand.batchTransferQuad(from, address(this), sizes, xs, ys, data); for (uint256 i = 0; i < sizes.length; i++) { _newLand.mintQuad(from, sizes[i], xs[i], ys[i], data); } } function burn(uint256[] calldata ids) external whenNotPaused { for (uint256 i = 0; i < ids.length; i++) { _oldLand.burn(ids[i]); } } function supportsInterface(bytes4 id) external pure returns (bool) { return id == 0x01ffc9a7 || id == 0x5e8bf644; } function setBatchMigration(address batchMigration) external onlyAdmin { _batchMigration = batchMigration; } // Empty storage space in contracts for future enhancements // ref: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/issues/13) uint256[49] private __gap; } /* solhint-disable func-order, code-complexity */ pragma solidity 0.5.9; import "./ERC721BaseToken.sol"; contract LandBaseToken is ERC721BaseToken { // Our grid is 408 x 408 lands uint256 internal constant GRID_SIZE = 408; uint256 internal constant LAYER = 0xFF00000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_1x1 = 0x0000000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_3x3 = 0x0100000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_6x6 = 0x0200000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_12x12 = 0x0300000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_24x24 = 0x0400000000000000000000000000000000000000000000000000000000000000; mapping(address => bool) internal _minters; event Minter(address superOperator, bool enabled); /// @notice Enable or disable the ability of `minter` to mint tokens /// @param minter address that will be given/removed minter right. /// @param enabled set whether the minter is enabled or disabled. function setMinter(address minter, bool enabled) external { require( msg.sender == _admin, "only admin is allowed to add minters" ); _minters[minter] = enabled; emit Minter(minter, enabled); } /// @notice check whether address `who` is given minter rights. /// @param who The address to query. /// @return whether the address has minter rights. function isMinter(address who) public view returns (bool) { return _minters[who]; } /// @notice total width of the map /// @return width function width() external returns(uint256) { return GRID_SIZE; } /// @notice total height of the map /// @return height function height() external returns(uint256) { return GRID_SIZE; } /// @notice x coordinate of Land token /// @param id tokenId /// @return the x coordinates function x(uint256 id) external returns(uint256) { require(_ownerOf(id) != address(0), "token does not exist"); return id % GRID_SIZE; } /// @notice y coordinate of Land token /// @param id tokenId /// @return the y coordinates function y(uint256 id) external returns(uint256) { require(_ownerOf(id) != address(0), "token does not exist"); return id / GRID_SIZE; } /** * @notice Mint a new quad (aligned to a quad tree with size 3, 6, 12 or 24 only) * @param to The recipient of the new quad * @param size The size of the new quad * @param x The top left x coordinate of the new quad * @param y The top left y coordinate of the new quad * @param data extra data to pass to the transfer */ function mintQuad(address to, uint256 size, uint256 x, uint256 y, bytes calldata data) external { require(to != address(0), "to is zero address"); require( isMinter(msg.sender), "Only a minter can mint" ); require(x % size == 0 && y % size == 0, "Invalid coordinates"); require(x <= GRID_SIZE - size && y <= GRID_SIZE - size, "Out of bounds"); uint256 quadId; uint256 id = x + y * GRID_SIZE; if (size == 1) { quadId = id; } else if (size == 3) { quadId = LAYER_3x3 + id; } else if (size == 6) { quadId = LAYER_6x6 + id; } else if (size == 12) { quadId = LAYER_12x12 + id; } else if (size == 24) { quadId = LAYER_24x24 + id; } else { require(false, "Invalid size"); } require(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == 0, "Already minted as 24x24"); uint256 toX = x+size; uint256 toY = y+size; if (size <= 12) { require( _owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == 0, "Already minted as 12x12" ); } else { for (uint256 x12i = x; x12i < toX; x12i += 12) { for (uint256 y12i = y; y12i < toY; y12i += 12) { uint256 id12x12 = LAYER_12x12 + x12i + y12i * GRID_SIZE; require(_owners[id12x12] == 0, "Already minted as 12x12"); } } } if (size <= 6) { require(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE] == 0, "Already minted as 6x6"); } else { for (uint256 x6i = x; x6i < toX; x6i += 6) { for (uint256 y6i = y; y6i < toY; y6i += 6) { uint256 id6x6 = LAYER_6x6 + x6i + y6i * GRID_SIZE; require(_owners[id6x6] == 0, "Already minted as 6x6"); } } } if (size <= 3) { require(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE] == 0, "Already minted as 3x3"); } else { for (uint256 x3i = x; x3i < toX; x3i += 3) { for (uint256 y3i = y; y3i < toY; y3i += 3) { uint256 id3x3 = LAYER_3x3 + x3i + y3i * GRID_SIZE; require(_owners[id3x3] == 0, "Already minted as 3x3"); } } } for (uint256 i = 0; i < size*size; i++) { uint256 id = _idInPath(i, size, x, y); require(_owners[id] == 0, "Already minted"); emit Transfer(address(0), to, id); } _owners[quadId] = uint256(to); _numNFTPerAddress[to] += size * size; _checkBatchReceiverAcceptQuad(msg.sender, address(0), to, size, x, y, data); } function _idInPath(uint256 i, uint256 size, uint256 x, uint256 y) internal pure returns(uint256) { uint256 row = i / size; if(row % 2 == 0) { // alow ids to follow a path in a quad return (x + (i%size)) + ((y + row) * GRID_SIZE); } else { return ((x + size) - (1 + i%size)) + ((y + row) * GRID_SIZE); } } /// @notice transfer one quad (aligned to a quad tree with size 3, 6, 12 or 24 only) /// @param from current owner of the quad /// @param to destination /// @param size size of the quad /// @param x The top left x coordinate of the quad /// @param y The top left y coordinate of the quad /// @param data additional data function transferQuad(address from, address to, uint256 size, uint256 x, uint256 y, bytes calldata data) external { require(from != address(0), "from is zero address"); require(to != address(0), "can't send to zero address"); bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; if (msg.sender != from && !metaTx) { require( _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "not authorized to transferQuad" ); } _transferQuad(from, to, size, x, y); _numNFTPerAddress[from] -= size * size; _numNFTPerAddress[to] += size * size; _checkBatchReceiverAcceptQuad(metaTx ? from : msg.sender, from, to, size, x, y, data); } function _checkBatchReceiverAcceptQuad( address operator, address from, address to, uint256 size, uint256 x, uint256 y, bytes memory data ) internal { if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) { uint256[] memory ids = new uint256[](size*size); for (uint256 i = 0; i < size*size; i++) { ids[i] = _idInPath(i, size, x, y); } require( _checkOnERC721BatchReceived(operator, from, to, ids, data), "erc721 batch transfer rejected by to" ); } } /// @notice transfer multiple quad (aligned to a quad tree with size 3, 6, 12 or 24 only) /// @param from current owner of the quad /// @param to destination /// @param sizes list of sizes for each quad /// @param xs list of top left x coordinates for each quad /// @param ys list of top left y coordinates for each quad /// @param data additional data function batchTransferQuad( address from, address to, uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data ) external { require(from != address(0), "from is zero address"); require(to != address(0), "can't send to zero address"); require(sizes.length == xs.length && xs.length == ys.length, "invalid data"); bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; if (msg.sender != from && !metaTx) { require( _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "not authorized to transferMultiQuads" ); } uint256 numTokensTransfered = 0; for (uint256 i = 0; i < sizes.length; i++) { uint256 size = sizes[i]; _transferQuad(from, to, size, xs[i], ys[i]); numTokensTransfered += size * size; } _numNFTPerAddress[from] -= numTokensTransfered; _numNFTPerAddress[to] += numTokensTransfered; if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) { uint256[] memory ids = new uint256[](numTokensTransfered); uint256 counter = 0; for (uint256 j = 0; j < sizes.length; j++) { uint256 size = sizes[j]; for (uint256 i = 0; i < size*size; i++) { ids[counter] = _idInPath(i, size, xs[j], ys[j]); counter++; } } require( _checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data), "erc721 batch transfer rejected by to" ); } } function _transferQuad(address from, address to, uint256 size, uint256 x, uint256 y) internal { if (size == 1) { uint256 id1x1 = x + y * GRID_SIZE; address owner = _ownerOf(id1x1); require(owner != address(0), "token does not exist"); require(owner == from, "not owner in _transferQuad"); _owners[id1x1] = uint256(to); } else { _regroup(from, to, size, x, y); } for (uint256 i = 0; i < size*size; i++) { emit Transfer(from, to, _idInPath(i, size, x, y)); } } function _checkAndClear(address from, uint256 id) internal returns(bool) { uint256 owner = _owners[id]; if (owner != 0) { require(address(owner) == from, "not owner"); _owners[id] = 0; return true; } return false; } function _regroup(address from, address to, uint256 size, uint256 x, uint256 y) internal { require(x % size == 0 && y % size == 0, "Invalid coordinates"); require(x <= GRID_SIZE - size && y <= GRID_SIZE - size, "Out of bounds"); if (size == 3) { _regroup3x3(from, to, x, y, true); } else if (size == 6) { _regroup6x6(from, to, x, y, true); } else if (size == 12) { _regroup12x12(from, to, x, y, true); } else if (size == 24) { _regroup24x24(from, to, x, y, true); } else { require(false, "Invalid size"); } } function _regroup3x3(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_3x3 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+3; xi++) { for (uint256 yi = y; yi < y+3; yi++) { ownerOfAll = _checkAndClear(from, xi + yi * GRID_SIZE) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from) || _owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE] == uint256(from) || _owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == uint256(from) || _owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from), "not owner of all sub quads nor parent quads" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll; } function _regroup6x6(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_6x6 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+6; xi += 3) { for (uint256 yi = y; yi < y+6; yi += 3) { bool ownAllIndividual = _regroup3x3(from, to, xi, yi, false); uint256 id3x3 = LAYER_3x3 + xi + yi * GRID_SIZE; uint256 owner3x3 = _owners[id3x3]; if (owner3x3 != 0) { if(!ownAllIndividual) { require(owner3x3 == uint256(from), "not owner of 3x3 quad"); } _owners[id3x3] = 0; } ownerOfAll = (ownAllIndividual || owner3x3 != 0) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from) || _owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == uint256(from) || _owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from), "not owner of all sub quads nor parent quads" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll; } function _regroup12x12(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_12x12 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+12; xi += 6) { for (uint256 yi = y; yi < y+12; yi += 6) { bool ownAllIndividual = _regroup6x6(from, to, xi, yi, false); uint256 id6x6 = LAYER_6x6 + xi + yi * GRID_SIZE; uint256 owner6x6 = _owners[id6x6]; if (owner6x6 != 0) { if(!ownAllIndividual) { require(owner6x6 == uint256(from), "not owner of 6x6 quad"); } _owners[id6x6] = 0; } ownerOfAll = (ownAllIndividual || owner6x6 != 0) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from) || _owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from), "not owner of all sub quads nor parent quads" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll; } function _regroup24x24(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_24x24 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+24; xi += 12) { for (uint256 yi = y; yi < y+24; yi += 12) { bool ownAllIndividual = _regroup12x12(from, to, xi, yi, false); uint256 id12x12 = LAYER_12x12 + xi + yi * GRID_SIZE; uint256 owner12x12 = _owners[id12x12]; if (owner12x12 != 0) { if(!ownAllIndividual) { require(owner12x12 == uint256(from), "not owner of 12x12 quad"); } _owners[id12x12] = 0; } ownerOfAll = (ownAllIndividual || owner12x12 != 0) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from), "not owner of all sub quads not parent quad" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll || _owners[quadId] == uint256(from); } function _ownerOf(uint256 id) internal view returns (address) { require(id & LAYER == 0, "Invalid token id"); uint256 x = id % GRID_SIZE; uint256 y = id / GRID_SIZE; uint256 owner1x1 = _owners[id]; if (owner1x1 != 0) { return address(owner1x1); // cast to zero } else { address owner3x3 = address(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE]); if (owner3x3 != address(0)) { return owner3x3; } else { address owner6x6 = address(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE]); if (owner6x6 != address(0)) { return owner6x6; } else { address owner12x12 = address(_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE]); if (owner12x12 != address(0)) { return owner12x12; } else { return address(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE]); } } } } } function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) { require(id & LAYER == 0, "Invalid token id"); uint256 x = id % GRID_SIZE; uint256 y = id / GRID_SIZE; uint256 owner1x1 = _owners[id]; if (owner1x1 != 0) { owner = address(owner1x1); operatorEnabled = (owner1x1 / 2**255) == 1; } else { address owner3x3 = address(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE]); if (owner3x3 != address(0)) { owner = owner3x3; operatorEnabled = false; } else { address owner6x6 = address(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE]); if (owner6x6 != address(0)) { owner = owner6x6; operatorEnabled = false; } else { address owner12x12 = address(_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE]); if (owner12x12 != address(0)) { owner = owner12x12; operatorEnabled = false; } else { owner = address(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE]); operatorEnabled = false; } } } } } } pragma solidity ^0.5.2; /** Note: The ERC-165 identifier for this interface is 0x5e8bf644. */ interface ERC721MandatoryTokenReceiver { function onERC721BatchReceived( address operator, address from, uint256[] calldata ids, bytes calldata data ) external returns (bytes4); // needs to return 0x4b808c46 function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); // needs to return 0x150b7a02 // needs to implements EIP-165 // function supportsInterface(bytes4 interfaceId) // external // view // returns (bool); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity 0.5.9; /// @dev minimal ERC2771 handler to keep bytecode-size down. /// based on: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/metatx/ERC2771Context.sol contract ERC2771Handler { address internal _trustedForwarder; function __ERC2771Handler_initialize(address forwarder) internal { _trustedForwarder = forwarder; } function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == _trustedForwarder; } function getTrustedForwarder() external view returns (address trustedForwarder) { return _trustedForwarder; } function _msgSender() internal view returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. // solhint-disable-next-line no-inline-assembly assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return msg.sender; } } } pragma solidity ^0.5.2; import "./Admin.sol"; /** * @title PausableWithAdmin * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract PausableWithAdmin is Admin { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the admin to pause, triggers stopped state */ function pause() public onlyAdmin whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the admin to unpause, returns to normal state */ function unpause() public onlyAdmin whenPaused { paused = false; emit Unpause(); } } /* solhint-disable func-order, code-complexity */ pragma solidity 0.5.9; import "../../contracts_common/Libraries/AddressUtils.sol"; import "../../contracts_common/Interfaces/ERC721TokenReceiver.sol"; import "../../contracts_common/Interfaces/ERC721Events.sol"; import "../../contracts_common/BaseWithStorage/SuperOperators.sol"; import "../../contracts_common/BaseWithStorage/MetaTransactionReceiver.sol"; import "../../contracts_common/Interfaces/ERC721MandatoryTokenReceiver.sol"; contract ERC721BaseToken is ERC721Events, SuperOperators, MetaTransactionReceiver { using AddressUtils for address; bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46; bytes4 internal constant ERC165ID = 0x01ffc9a7; bytes4 internal constant ERC721_MANDATORY_RECEIVER = 0x5e8bf644; mapping (address => uint256) public _numNFTPerAddress; mapping (uint256 => uint256) public _owners; mapping (address => mapping(address => bool)) public _operatorsForAll; mapping (uint256 => address) public _operators; bool internal _initialized; modifier initializer() { require(!_initialized, "ERC721BaseToken: Contract already initialized"); _; } function initialize ( address metaTransactionContract, address admin ) public initializer { _admin = admin; _setMetaTransactionProcessor(metaTransactionContract, true); _initialized = true; } function _transferFrom(address from, address to, uint256 id) internal { _numNFTPerAddress[from]--; _numNFTPerAddress[to]++; _owners[id] = uint256(to); emit Transfer(from, to, id); } /** * @notice Return the number of Land owned by an address * @param owner The address to look for * @return The number of Land token owned by the address */ function balanceOf(address owner) external view returns (uint256) { require(owner != address(0), "owner is zero address"); return _numNFTPerAddress[owner]; } function _ownerOf(uint256 id) internal view returns (address) { return address(_owners[id]); } function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) { uint256 data = _owners[id]; owner = address(data); operatorEnabled = (data / 2**255) == 1; } /** * @notice Return the owner of a Land * @param id The id of the Land * @return The address of the owner */ function ownerOf(uint256 id) external view returns (address owner) { owner = _ownerOf(id); require(owner != address(0), "token does not exist"); } function _approveFor(address owner, address operator, uint256 id) internal { if(operator == address(0)) { _owners[id] = uint256(owner); // no need to resset the operator, it will be overriden next time } else { _owners[id] = uint256(owner) + 2**255; _operators[id] = operator; } emit Approval(owner, operator, id); } /** * @notice Approve an operator to spend tokens on the sender behalf * @param sender The address giving the approval * @param operator The address receiving the approval * @param id The id of the token */ function approveFor( address sender, address operator, uint256 id ) external { address owner = _ownerOf(id); require(sender != address(0), "sender is zero address"); require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[sender][msg.sender], "not authorized to approve" ); require(owner == sender, "owner != sender"); _approveFor(owner, operator, id); } /** * @notice Approve an operator to spend tokens on the sender behalf * @param operator The address receiving the approval * @param id The id of the token */ function approve(address operator, uint256 id) external { address owner = _ownerOf(id); require(owner != address(0), "token does not exist"); require( owner == msg.sender || _superOperators[msg.sender] || _operatorsForAll[owner][msg.sender], "not authorized to approve" ); _approveFor(owner, operator, id); } /** * @notice Get the approved operator for a specific token * @param id The id of the token * @return The address of the operator */ function getApproved(uint256 id) external view returns (address) { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "token does not exist"); if (operatorEnabled) { return _operators[id]; } else { return address(0); } } function _checkTransfer(address from, address to, uint256 id) internal view returns (bool isMetaTx) { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "token does not exist"); require(owner == from, "not owner in _checkTransfer"); require(to != address(0), "can't send to zero address"); isMetaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; if (msg.sender != from && !isMetaTx) { require( _superOperators[msg.sender] || _operatorsForAll[from][msg.sender] || (operatorEnabled && _operators[id] == msg.sender), "not approved to transfer" ); } } function _checkInterfaceWith10000Gas(address _contract, bytes4 interfaceId) internal view returns (bool) { bool success; bool result; bytes memory call_data = abi.encodeWithSelector( ERC165ID, interfaceId ); // solium-disable-next-line security/no-inline-assembly assembly { let call_ptr := add(0x20, call_data) let call_size := mload(call_data) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall( 10000, _contract, call_ptr, call_size, output, 0x20 ) // 32 bytes result := mload(output) } // (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas assert(gasleft() > 158); return success && result; } /** * @notice Transfer a token between 2 addresses * @param from The sender of the token * @param to The recipient of the token * @param id The id of the token */ function transferFrom(address from, address to, uint256 id) external { bool metaTx = _checkTransfer(from, to, id); _transferFrom(from, to, id); if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) { require( _checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, ""), "erc721 transfer rejected by to" ); } } /** * @notice Transfer a token between 2 addresses letting the receiver knows of the transfer * @param from The sender of the token * @param to The recipient of the token * @param id The id of the token * @param data Additional data */ function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public { bool metaTx = _checkTransfer(from, to, id); _transferFrom(from, to, id); if (to.isContract()) { require( _checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, data), "ERC721: transfer rejected by to" ); } } /** * @notice Transfer a token between 2 addresses letting the receiver knows of the transfer * @param from The send of the token * @param to The recipient of the token * @param id The id of the token */ function safeTransferFrom(address from, address to, uint256 id) external { safeTransferFrom(from, to, id, ""); } /** * @notice Transfer many tokens between 2 addresses * @param from The sender of the token * @param to The recipient of the token * @param ids The ids of the tokens * @param data additional data */ function batchTransferFrom(address from, address to, uint256[] calldata ids, bytes calldata data) external { _batchTransferFrom(from, to, ids, data, false); } function _batchTransferFrom(address from, address to, uint256[] memory ids, bytes memory data, bool safe) internal { bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; bool authorized = msg.sender == from || metaTx || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender]; require(from != address(0), "from is zero address"); require(to != address(0), "can't send to zero address"); uint256 numTokens = ids.length; for(uint256 i = 0; i < numTokens; i ++) { uint256 id = ids[i]; (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner == from, "not owner in batchTransferFrom"); require(authorized || (operatorEnabled && _operators[id] == msg.sender), "not authorized"); _owners[id] = uint256(to); emit Transfer(from, to, id); } if (from != to) { _numNFTPerAddress[from] -= numTokens; _numNFTPerAddress[to] += numTokens; } if (to.isContract() && (safe || _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER))) { require( _checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data), "erc721 batch transfer rejected by to" ); } } /** * @notice Transfer many tokens between 2 addresses ensuring the receiving contract has a receiver method * @param from The sender of the token * @param to The recipient of the token * @param ids The ids of the tokens * @param data additional data */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, bytes calldata data) external { _batchTransferFrom(from, to, ids, data, true); } /** * @notice Check if the contract supports an interface * 0x01ffc9a7 is ERC-165 * 0x80ac58cd is ERC-721 * @param id The id of the interface * @return True if the interface is supported */ function supportsInterface(bytes4 id) external pure returns (bool) { return id == 0x01ffc9a7 || id == 0x80ac58cd; } /** * @notice Set the approval for an operator to manage all the tokens of the sender * @param sender The address giving the approval * @param operator The address receiving the approval * @param approved The determination of the approval */ function setApprovalForAllFor( address sender, address operator, bool approved ) external { require(sender != address(0), "Invalid sender address"); require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender], "not authorized to approve for all" ); _setApprovalForAll(sender, operator, approved); } /** * @notice Set the approval for an operator to manage all the tokens of the sender * @param operator The address receiving the approval * @param approved The determination of the approval */ function setApprovalForAll(address operator, bool approved) external { _setApprovalForAll(msg.sender, operator, approved); } function _setApprovalForAll( address sender, address operator, bool approved ) internal { require( !_superOperators[operator], "super operator can't have their approvalForAll changed" ); _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /** * @notice Check if the sender approved the operator * @param owner The address of the owner * @param operator The address of the operator * @return The status of the approval */ function isApprovedForAll(address owner, address operator) external view returns (bool isOperator) { return _operatorsForAll[owner][operator] || _superOperators[operator]; } function _burn(address from, address owner, uint256 id) internal { require(from == owner, "not owner"); _owners[id] = 2**160; // cannot mint it again _numNFTPerAddress[from]--; emit Transfer(from, address(0), id); } /// @notice Burns token `id`. /// @param id token which will be burnt. function burn(uint256 id) external { _burn(msg.sender, _ownerOf(id), id); } /// @notice Burn token`id` from `from`. /// @param from address whose token is to be burnt. /// @param id token which will be burnt. function burnFrom(address from, uint256 id) external { require(from != address(0), "Invalid sender address"); (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require( msg.sender == from || _metaTransactionContracts[msg.sender] || (operatorEnabled && _operators[id] == msg.sender) || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "not authorized to burn" ); _burn(from, owner, id); } function _checkOnERC721Received(address operator, address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { bytes4 retval = ERC721TokenReceiver(to).onERC721Received(operator, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } function _checkOnERC721BatchReceived(address operator, address from, address to, uint256[] memory ids, bytes memory _data) internal returns (bool) { bytes4 retval = ERC721MandatoryTokenReceiver(to).onERC721BatchReceived(operator, from, ids, _data); return (retval == _ERC721_BATCH_RECEIVED); } // Empty storage space in contracts for future enhancements // ref: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/issues/13) uint256[49] private __gap; } pragma solidity ^0.5.2; library AddressUtils { function toPayable(address _address) internal pure returns (address payable _payable) { return address(uint160(_address)); } function isContract(address addr) internal view returns (bool) { // for accounts without code, i.e. `keccak256('')`: bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; // solium-disable-next-line security/no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != accountHash); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity ^0.5.2; interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.5.2; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://eips.ethereum.org/EIPS/eip-721 */ interface ERC721Events { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); } pragma solidity ^0.5.2; import "./Admin.sol"; contract SuperOperators is Admin { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external { require( msg.sender == _admin, "only admin is allowed to add super operators" ); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } } pragma solidity ^0.5.2; import "./Admin.sol"; contract MetaTransactionReceiver is Admin{ mapping(address => bool) internal _metaTransactionContracts; event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled); /// @notice Enable or disable the ability of `metaTransactionProcessor` to perform meta-tx (metaTransactionProcessor rights). /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. function setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) public { require( msg.sender == _admin, "only admin can setup metaTransactionProcessors" ); _setMetaTransactionProcessor(metaTransactionProcessor, enabled); } function _setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) internal { _metaTransactionContracts[metaTransactionProcessor] = enabled; emit MetaTransactionProcessor(metaTransactionProcessor, enabled); } /// @notice check whether address `who` is given meta-transaction execution rights. /// @param who The address to query. /// @return whether the address has meta-transaction execution rights. function isMetaTransactionProcessor(address who) external view returns(bool) { return _metaTransactionContracts[who]; } } pragma solidity ^0.5.2; contract Admin { address internal _admin; event AdminChanged(address oldAdmin, address newAdmin); /// @notice gives the current administrator of this contract. /// @return the current administrator of this contract. function getAdmin() external view returns (address) { return _admin; } /// @notice change the administrator to be `newAdmin`. /// @param newAdmin address of the new administrator. function changeAdmin(address newAdmin) external { require(msg.sender == _admin, "only admin can change admin"); emit AdminChanged(_admin, newAdmin); _admin = newAdmin; } modifier onlyAdmin() { require (msg.sender == _admin, "only admin allowed"); _; } }
check whether address `who` is given minter rights. who The address to query. return whether the address has minter rights.
function isMinter(address who) public view returns (bool) { return _minters[who]; }
1,471,356
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./Proposals.sol"; /** * @title Ballot * @dev Implements voting process along with vote delegation */ interface TokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } contract Ballot is Proposals{ struct Voter { uint lockedTokens; uint[4] allocatedVotes; // # votes allocated to voter, 0=LMIP, 1=Maintenance, 2=POC, 3=Continuing bool[4] voted; // if true, that person already voted, 0=LMIP, 1=Maintenance, 2=POC, 3=Continuing address[4] delegate; // person delegated to, 0=LMIP, 1=Maintenance, 2=POC, 3=Continuing uint[] lmipVotes; // indices of the selected proposals uint[] maintenanceVotes; uint[] pocVotes; uint[] continuingVotes; uint registrationDate; } TokenInterface internal VotingToken; enum ProposalType { LMIP, Maintenance, POC, Continuing } mapping(address => Voter) public voters; mapping(address => bool) public registered; Proposal[] public lmipProposals; Proposal[] public maintenanceProposals; Proposal[] public pocProposals; Proposal[] public continuingProposals; constructor(address votingTokenAddress) public { VotingToken = TokenInterface(votingTokenAddress); } function addProposal(bytes32 name, uint256 fileHash, string memory fileURI, uint fundingRequest, address payable recipient, ProposalType proposalType) public { } function addLMIPProposal(Proposal memory proposal) internal { } function addMaintencanceProposal(Proposal memory proposal) internal { } function addPOCProposal(Proposal memory proposal) internal { } function addContinuingProposal(Proposal memory proposal) internal { } function getVotingTokenBalance() public view returns(uint){ return VotingToken.balanceOf(msg.sender); } function getAllowance() public view returns (uint256 remaining) { return VotingToken.allowance(msg.sender, address(this)); } // The Ballot will authorize the amount in the user's wallet at time of registration. // Ensure all funds to be used for voting are present in wallet before registering function registerToVote() public { require(registered[msg.sender] == false, "Already registered"); registered[msg.sender] = true; Voter storage sender = voters[msg.sender]; sender.registrationDate = block.timestamp; //TODO: set total votes to current balance or approval value, whichever is lower } function transfer() public { VotingToken.transferFrom(msg.sender, address(this), 100000000); } function withdraw() public { VotingToken.transferFrom(address(this), msg.sender, address(this).balance); } /** * @dev Delegate your vote to the voter 'to'. * @param to address to which vote is delegated */ function delegateAll(address to) public { delegateLMIPVote(to); delegateMaintenanceVote(to); delegatePOCVote(to); delegateContinuingVote(to); } function delegateLMIPVote(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted[0], "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate[0] != address(0)) { to = voters[to].delegate[0]; // We found a loop in the delegation, not allowed. require(to != msg.sender, "Found loop in LMIP delegation."); } sender.voted[0] = true; sender.delegate[0] = to; Voter storage delegate_ = voters[to]; if (delegate_.voted[0]) { // //TODO: // // If the delegate already voted, // directly add to the number of votes } else { // If the delegate did not vote yet, // add to her weight. delegate_.allocatedVotes[0] += sender.allocatedVotes[0]; } sender.allocatedVotes[0] = 0; } function delegateMaintenanceVote(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted[1], "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate[1] != address(0)) { to = voters[to].delegate[1]; require(to != msg.sender, "Found loop in maintenance delegation."); } sender.voted[1] = true; sender.delegate[1] = to; Voter storage delegate_ = voters[to]; if (delegate_.voted[1]) { // //TODO: // // If the delegate already voted, // directly add to the number of votes } else { delegate_.allocatedVotes[1] += sender.allocatedVotes[1]; } sender.allocatedVotes[1] = 0; } function delegatePOCVote(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted[2], "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate[2] != address(0)) { to = voters[to].delegate[2]; require(to != msg.sender, "Found loop in POC delegation."); } sender.voted[2] = true; sender.delegate[2] = to; Voter storage delegate_ = voters[to]; if (delegate_.voted[2]) { // //TODO: // // If the delegate already voted, // directly add to the number of votes } else { delegate_.allocatedVotes[2] += sender.allocatedVotes[2]; } sender.allocatedVotes[2] = 0; } function delegateContinuingVote(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted[3], "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate[3] != address(0)) { to = voters[to].delegate[3]; require(to != msg.sender, "Found loop in POC delegation."); } sender.voted[3] = true; sender.delegate[3] = to; Voter storage delegate_ = voters[to]; if (delegate_.voted[3]) { // //TODO: // // If the delegate already voted, // directly add to the number of votes } else { delegate_.allocatedVotes[3] += sender.allocatedVotes[3]; } sender.allocatedVotes[3] = 0; } function submitVotes(uint[] memory lmipVotes, uint[] memory maintenanceVotes, uint[] memory pocVotes, uint[] memory continuingVotes) public { Voter memory sender = voters[msg.sender]; if(sender.allocatedVotes[0] != 0){ voteLMIP(lmipVotes); } if(sender.allocatedVotes[1] != 0){ voteMaintenance(maintenanceVotes); } if(sender.allocatedVotes[2] != 0){ votePOC(pocVotes); } if(sender.allocatedVotes[3] != 0){ voteContinuing(continuingVotes); } } function voteLMIP(uint[] memory lmipVotes) public { Voter storage sender = voters[msg.sender]; require(sender.allocatedVotes[0] != 0, "Has no right to vote"); require(!sender.voted[0], "Already voted."); sender.voted[0] = true; sender.lmipVotes = lmipVotes; // // //TODO: apply appropriate votes to each proposal selected // // } function voteMaintenance(uint[] memory maintenanceVotes) public { Voter storage sender = voters[msg.sender]; require(sender.allocatedVotes[1] != 0, "Has no right to vote"); require(!sender.voted[1], "Already voted."); sender.voted[1] = true; sender.maintenanceVotes = maintenanceVotes; // // //TODO: apply appropriate votes to each proposal selected // // } function votePOC(uint[] memory pocVotes) public { Voter storage sender = voters[msg.sender]; require(sender.allocatedVotes[2] != 0, "Has no right to vote"); require(!sender.voted[2], "Already voted."); sender.voted[2] = true; sender.pocVotes = pocVotes; // // //TODO: apply appropriate votes to each proposal selected // // } function voteContinuing(uint[] memory continuingVotes) public { Voter storage sender = voters[msg.sender]; require(sender.allocatedVotes[3] != 0, "Has no right to vote"); require(!sender.voted[3], "Already voted."); sender.voted[3] = true; sender.continuingVotes = continuingVotes; // // //TODO: apply appropriate votes to each proposal selected // // } /** * @dev Computes the winning proposal taking all previous votes into account. * @return winningProposal_ index of winning proposal in the proposals array */ function winningProposal(ProposalType proposalType) public view returns (uint winningProposal_) { uint winningVoteCount = 0; if(proposalType == ProposalType.LMIP) { for (uint p = 0; p < lmipProposals.length; p++) { if (lmipProposals[p].voteCount > winningVoteCount) { winningVoteCount = lmipProposals[p].voteCount; winningProposal_ = p; } } } } /** * @dev Calls winningProposal() function to get the index of the winner contained in the proposals array and then * @return winnerName_ the name of the winner */ function winnerName(ProposalType proposalType) public view returns (bytes32 winnerName_) { if(proposalType == ProposalType.LMIP){ winnerName_ = lmipProposals[winningProposal(proposalType)].name; } } }
TODO: If the delegate already voted, directly add to the number of votes
function delegateMaintenanceVote(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted[1], "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate[1] != address(0)) { to = voters[to].delegate[1]; require(to != msg.sender, "Found loop in maintenance delegation."); } sender.voted[1] = true; sender.delegate[1] = to; Voter storage delegate_ = voters[to]; if (delegate_.voted[1]) { delegate_.allocatedVotes[1] += sender.allocatedVotes[1]; } sender.allocatedVotes[1] = 0; }
14,065,432
// Grove v0.2 /// @title GroveLib - Library for queriable indexed ordered data. /// @author PiperMerriam - library GroveLib { /* * Indexes for ordered data * * Address: 0x7c1eb207c07e7ab13cf245585bd03d0fa478d034 */ struct Index { bytes32 root; mapping (bytes32 => Node) nodes; } struct Node { bytes32 id; int value; bytes32 parent; bytes32 left; bytes32 right; uint height; } function max(uint a, uint b) internal returns (uint) { if (a >= b) { return a; } return b; } /* * Node getters */ /// @dev Retrieve the unique identifier for the node. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNodeId(Index storage index, bytes32 id) constant returns (bytes32) { return index.nodes[id].id; } /// @dev Retrieve the value for the node. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNodeValue(Index storage index, bytes32 id) constant returns (int) { return index.nodes[id].value; } /// @dev Retrieve the height of the node. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNodeHeight(Index storage index, bytes32 id) constant returns (uint) { return index.nodes[id].height; } /// @dev Retrieve the parent id of the node. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNodeParent(Index storage index, bytes32 id) constant returns (bytes32) { return index.nodes[id].parent; } /// @dev Retrieve the left child id of the node. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNodeLeftChild(Index storage index, bytes32 id) constant returns (bytes32) { return index.nodes[id].left; } /// @dev Retrieve the right child id of the node. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNodeRightChild(Index storage index, bytes32 id) constant returns (bytes32) { return index.nodes[id].right; } /// @dev Retrieve the node id of the next node in the tree. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getPreviousNode(Index storage index, bytes32 id) constant returns (bytes32) { Node storage currentNode = index.nodes[id]; if (currentNode.id == 0x0) { // Unknown node, just return 0x0; return 0x0; } Node memory child; if (currentNode.left != 0x0) { // Trace left to latest child in left tree. child = index.nodes[currentNode.left]; while (child.right != 0) { child = index.nodes[child.right]; } return child.id; } if (currentNode.parent != 0x0) { // Now we trace back up through parent relationships, looking // for a link where the child is the right child of it's // parent. Node storage parent = index.nodes[currentNode.parent]; child = currentNode; while (true) { if (parent.right == child.id) { return parent.id; } if (parent.parent == 0x0) { break; } child = parent; parent = index.nodes[parent.parent]; } } // This is the first node, and has no previous node. return 0x0; } /// @dev Retrieve the node id of the previous node in the tree. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up. function getNextNode(Index storage index, bytes32 id) constant returns (bytes32) { Node storage currentNode = index.nodes[id]; if (currentNode.id == 0x0) { // Unknown node, just return 0x0; return 0x0; } Node memory child; if (currentNode.right != 0x0) { // Trace right to earliest child in right tree. child = index.nodes[currentNode.right]; while (child.left != 0) { child = index.nodes[child.left]; } return child.id; } if (currentNode.parent != 0x0) { // if the node is the left child of it's parent, then the // parent is the next one. Node storage parent = index.nodes[currentNode.parent]; child = currentNode; while (true) { if (parent.left == child.id) { return parent.id; } if (parent.parent == 0x0) { break; } child = parent; parent = index.nodes[parent.parent]; } // Now we need to trace all the way up checking to see if any parent is the } // This is the final node. return 0x0; } /// @dev Updates or Inserts the id into the index at its appropriate location based on the value provided. /// @param index The index that the node is part of. /// @param id The unique identifier of the data element the index node will represent. /// @param value The value of the data element that represents it's total ordering with respect to other elementes. function insert(Index storage index, bytes32 id, int value) public { if (index.nodes[id].id == id) { // A node with this id already exists. If the value is // the same, then just return early, otherwise, remove it // and reinsert it. if (index.nodes[id].value == value) { return; } remove(index, id); } uint leftHeight; uint rightHeight; bytes32 previousNodeId = 0x0; if (index.root == 0x0) { index.root = id; } Node storage currentNode = index.nodes[index.root]; // Do insertion while (true) { if (currentNode.id == 0x0) { // This is a new unpopulated node. currentNode.id = id; currentNode.parent = previousNodeId; currentNode.value = value; break; } // Set the previous node id. previousNodeId = currentNode.id; // The new node belongs in the right subtree if (value >= currentNode.value) { if (currentNode.right == 0x0) { currentNode.right = id; } currentNode = index.nodes[currentNode.right]; continue; } // The new node belongs in the left subtree. if (currentNode.left == 0x0) { currentNode.left = id; } currentNode = index.nodes[currentNode.left]; } // Rebalance the tree _rebalanceTree(index, currentNode.id); } /// @dev Checks whether a node for the given unique identifier exists within the given index. /// @param index The index that should be searched /// @param id The unique identifier of the data element to check for. function exists(Index storage index, bytes32 id) constant returns (bool) { return (index.nodes[id].height > 0); } /// @dev Remove the node for the given unique identifier from the index. /// @param index The index that should be removed /// @param id The unique identifier of the data element to remove. function remove(Index storage index, bytes32 id) public { Node storage replacementNode; Node storage parent; Node storage child; bytes32 rebalanceOrigin; Node storage nodeToDelete = index.nodes[id]; if (nodeToDelete.id != id) { // The id does not exist in the tree. return; } if (nodeToDelete.left != 0x0 || nodeToDelete.right != 0x0) { // This node is not a leaf node and thus must replace itself in // it's tree by either the previous or next node. if (nodeToDelete.left != 0x0) { // This node is guaranteed to not have a right child. replacementNode = index.nodes[getPreviousNode(index, nodeToDelete.id)]; } else { // This node is guaranteed to not have a left child. replacementNode = index.nodes[getNextNode(index, nodeToDelete.id)]; } // The replacementNode is guaranteed to have a parent. parent = index.nodes[replacementNode.parent]; // Keep note of the location that our tree rebalancing should // start at. rebalanceOrigin = replacementNode.id; // Join the parent of the replacement node with any subtree of // the replacement node. We can guarantee that the replacement // node has at most one subtree because of how getNextNode and // getPreviousNode are used. if (parent.left == replacementNode.id) { parent.left = replacementNode.right; if (replacementNode.right != 0x0) { child = index.nodes[replacementNode.right]; child.parent = parent.id; } } if (parent.right == replacementNode.id) { parent.right = replacementNode.left; if (replacementNode.left != 0x0) { child = index.nodes[replacementNode.left]; child.parent = parent.id; } } // Now we replace the nodeToDelete with the replacementNode. // This includes parent/child relationships for all of the // parent, the left child, and the right child. replacementNode.parent = nodeToDelete.parent; if (nodeToDelete.parent != 0x0) { parent = index.nodes[nodeToDelete.parent]; if (parent.left == nodeToDelete.id) { parent.left = replacementNode.id; } if (parent.right == nodeToDelete.id) { parent.right = replacementNode.id; } } else { // If the node we are deleting is the root node update the // index root node pointer. index.root = replacementNode.id; } replacementNode.left = nodeToDelete.left; if (nodeToDelete.left != 0x0) { child = index.nodes[nodeToDelete.left]; child.parent = replacementNode.id; } replacementNode.right = nodeToDelete.right; if (nodeToDelete.right != 0x0) { child = index.nodes[nodeToDelete.right]; child.parent = replacementNode.id; } } else if (nodeToDelete.parent != 0x0) { // The node being deleted is a leaf node so we only erase it's // parent linkage. parent = index.nodes[nodeToDelete.parent]; if (parent.left == nodeToDelete.id) { parent.left = 0x0; } if (parent.right == nodeToDelete.id) { parent.right = 0x0; } // keep note of where the rebalancing should begin. rebalanceOrigin = parent.id; } else { // This is both a leaf node and the root node, so we need to // unset the root node pointer. index.root = 0x0; } // Now we zero out all of the fields on the nodeToDelete. nodeToDelete.id = 0x0; nodeToDelete.value = 0; nodeToDelete.parent = 0x0; nodeToDelete.left = 0x0; nodeToDelete.right = 0x0; nodeToDelete.height = 0; // Walk back up the tree rebalancing if (rebalanceOrigin != 0x0) { _rebalanceTree(index, rebalanceOrigin); } } bytes2 constant GT = ">"; bytes2 constant LT = "<"; bytes2 constant GTE = ">="; bytes2 constant LTE = "<="; bytes2 constant EQ = "=="; function _compare(int left, bytes2 operator, int right) internal returns (bool) { if (operator == GT) { return (left > right); } if (operator == LT) { return (left < right); } if (operator == GTE) { return (left >= right); } if (operator == LTE) { return (left <= right); } if (operator == EQ) { return (left == right); } // Invalid operator. throw; } function _getMaximum(Index storage index, bytes32 id) internal returns (int) { Node storage currentNode = index.nodes[id]; while (true) { if (currentNode.right == 0x0) { return currentNode.value; } currentNode = index.nodes[currentNode.right]; } } function _getMinimum(Index storage index, bytes32 id) internal returns (int) { Node storage currentNode = index.nodes[id]; while (true) { if (currentNode.left == 0x0) { return currentNode.value; } currentNode = index.nodes[currentNode.left]; } } /** @dev Query the index for the edge-most node that satisfies the * given query. For >, >=, and ==, this will be the left-most node * that satisfies the comparison. For < and <= this will be the * right-most node that satisfies the comparison. */ /// @param index The index that should be queried /** @param operator One of '>', '>=', '<', '<=', '==' to specify what * type of comparison operator should be used. */ function query(Index storage index, bytes2 operator, int value) public returns (bytes32) { bytes32 rootNodeId = index.root; if (rootNodeId == 0x0) { // Empty tree. return 0x0; } Node storage currentNode = index.nodes[rootNodeId]; while (true) { if (_compare(currentNode.value, operator, value)) { // We have found a match but it might not be the // *correct* match. if ((operator == LT) || (operator == LTE)) { // Need to keep traversing right until this is no // longer true. if (currentNode.right == 0x0) { return currentNode.id; } if (_compare(_getMinimum(index, currentNode.right), operator, value)) { // There are still nodes to the right that // match. currentNode = index.nodes[currentNode.right]; continue; } return currentNode.id; } if ((operator == GT) || (operator == GTE) || (operator == EQ)) { // Need to keep traversing left until this is no // longer true. if (currentNode.left == 0x0) { return currentNode.id; } if (_compare(_getMaximum(index, currentNode.left), operator, value)) { currentNode = index.nodes[currentNode.left]; continue; } return currentNode.id; } } if ((operator == LT) || (operator == LTE)) { if (currentNode.left == 0x0) { // There are no nodes that are less than the value // so return null. return 0x0; } currentNode = index.nodes[currentNode.left]; continue; } if ((operator == GT) || (operator == GTE)) { if (currentNode.right == 0x0) { // There are no nodes that are greater than the value // so return null. return 0x0; } currentNode = index.nodes[currentNode.right]; continue; } if (operator == EQ) { if (currentNode.value < value) { if (currentNode.right == 0x0) { return 0x0; } currentNode = index.nodes[currentNode.right]; continue; } if (currentNode.value > value) { if (currentNode.left == 0x0) { return 0x0; } currentNode = index.nodes[currentNode.left]; continue; } } } } function _rebalanceTree(Index storage index, bytes32 id) internal { // Trace back up rebalancing the tree and updating heights as // needed.. Node storage currentNode = index.nodes[id]; while (true) { int balanceFactor = _getBalanceFactor(index, currentNode.id); if (balanceFactor == 2) { // Right rotation (tree is heavy on the left) if (_getBalanceFactor(index, currentNode.left) == -1) { // The subtree is leaning right so it need to be // rotated left before the current node is rotated // right. _rotateLeft(index, currentNode.left); } _rotateRight(index, currentNode.id); } if (balanceFactor == -2) { // Left rotation (tree is heavy on the right) if (_getBalanceFactor(index, currentNode.right) == 1) { // The subtree is leaning left so it need to be // rotated right before the current node is rotated // left. _rotateRight(index, currentNode.right); } _rotateLeft(index, currentNode.id); } if ((-1 <= balanceFactor) && (balanceFactor <= 1)) { _updateNodeHeight(index, currentNode.id); } if (currentNode.parent == 0x0) { // Reached the root which may be new due to tree // rotation, so set it as the root and then break. break; } currentNode = index.nodes[currentNode.parent]; } } function _getBalanceFactor(Index storage index, bytes32 id) internal returns (int) { Node storage node = index.nodes[id]; return int(index.nodes[node.left].height) - int(index.nodes[node.right].height); } function _updateNodeHeight(Index storage index, bytes32 id) internal { Node storage node = index.nodes[id]; node.height = max(index.nodes[node.left].height, index.nodes[node.right].height) + 1; } function _rotateLeft(Index storage index, bytes32 id) internal { Node storage originalRoot = index.nodes[id]; if (originalRoot.right == 0x0) { // Cannot rotate left if there is no right originalRoot to rotate into // place. throw; } // The right child is the new root, so it gets the original // `originalRoot.parent` as it's parent. Node storage newRoot = index.nodes[originalRoot.right]; newRoot.parent = originalRoot.parent; // The original root needs to have it's right child nulled out. originalRoot.right = 0x0; if (originalRoot.parent != 0x0) { // If there is a parent node, it needs to now point downward at // the newRoot which is rotating into the place where `node` was. Node storage parent = index.nodes[originalRoot.parent]; // figure out if we're a left or right child and have the // parent point to the new node. if (parent.left == originalRoot.id) { parent.left = newRoot.id; } if (parent.right == originalRoot.id) { parent.right = newRoot.id; } } if (newRoot.left != 0) { // If the new root had a left child, that moves to be the // new right child of the original root node Node storage leftChild = index.nodes[newRoot.left]; originalRoot.right = leftChild.id; leftChild.parent = originalRoot.id; } // Update the newRoot's left node to point at the original node. originalRoot.parent = newRoot.id; newRoot.left = originalRoot.id; if (newRoot.parent == 0x0) { index.root = newRoot.id; } // TODO: are both of these updates necessary? _updateNodeHeight(index, originalRoot.id); _updateNodeHeight(index, newRoot.id); } function _rotateRight(Index storage index, bytes32 id) internal { Node storage originalRoot = index.nodes[id]; if (originalRoot.left == 0x0) { // Cannot rotate right if there is no left node to rotate into // place. throw; } // The left child is taking the place of node, so we update it's // parent to be the original parent of the node. Node storage newRoot = index.nodes[originalRoot.left]; newRoot.parent = originalRoot.parent; // Null out the originalRoot.left originalRoot.left = 0x0; if (originalRoot.parent != 0x0) { // If the node has a parent, update the correct child to point // at the newRoot now. Node storage parent = index.nodes[originalRoot.parent]; if (parent.left == originalRoot.id) { parent.left = newRoot.id; } if (parent.right == originalRoot.id) { parent.right = newRoot.id; } } if (newRoot.right != 0x0) { Node storage rightChild = index.nodes[newRoot.right]; originalRoot.left = newRoot.right; rightChild.parent = originalRoot.id; } // Update the new root's right node to point to the original node. originalRoot.parent = newRoot.id; newRoot.right = originalRoot.id; if (newRoot.parent == 0x0) { index.root = newRoot.id; } // Recompute heights. _updateNodeHeight(index, originalRoot.id); _updateNodeHeight(index, newRoot.id); } } // Accounting v0.1 (not the same as the 0.1 release of this library) /// @title Accounting Lib - Accounting utilities /// @author Piper Merriam - library AccountingLib { /* * Address: 0x89efe605e9ecbe22849cd85d5449cc946c26f8f3 */ struct Bank { mapping (address => uint) accountBalances; } /// @dev Low level method for adding funds to an account. Protects against overflow. /// @param self The Bank instance to operate on. /// @param accountAddress The address of the account the funds should be added to. /// @param value The amount that should be added to the account. function addFunds(Bank storage self, address accountAddress, uint value) public { if (self.accountBalances[accountAddress] + value < self.accountBalances[accountAddress]) { // Prevent Overflow. throw; } self.accountBalances[accountAddress] += value; } event _Deposit(address indexed _from, address indexed accountAddress, uint value); /// @dev Function wrapper around the _Deposit event so that it can be used by contracts. Can be used to log a deposit to an account. /// @param _from The address that deposited the funds. /// @param accountAddress The address of the account the funds were added to. /// @param value The amount that was added to the account. function Deposit(address _from, address accountAddress, uint value) public { _Deposit(_from, accountAddress, value); } /// @dev Safe function for depositing funds. Returns boolean for whether the deposit was successful /// @param self The Bank instance to operate on. /// @param accountAddress The address of the account the funds should be added to. /// @param value The amount that should be added to the account. function deposit(Bank storage self, address accountAddress, uint value) public returns (bool) { addFunds(self, accountAddress, value); return true; } event _Withdrawal(address indexed accountAddress, uint value); /// @dev Function wrapper around the _Withdrawal event so that it can be used by contracts. Can be used to log a withdrawl from an account. /// @param accountAddress The address of the account the funds were withdrawn from. /// @param value The amount that was withdrawn to the account. function Withdrawal(address accountAddress, uint value) public { _Withdrawal(accountAddress, value); } event _InsufficientFunds(address indexed accountAddress, uint value, uint balance); /// @dev Function wrapper around the _InsufficientFunds event so that it can be used by contracts. Can be used to log a failed withdrawl from an account. /// @param accountAddress The address of the account the funds were to be withdrawn from. /// @param value The amount that was attempted to be withdrawn from the account. /// @param balance The current balance of the account. function InsufficientFunds(address accountAddress, uint value, uint balance) public { _InsufficientFunds(accountAddress, value, balance); } /// @dev Low level method for removing funds from an account. Protects against underflow. /// @param self The Bank instance to operate on. /// @param accountAddress The address of the account the funds should be deducted from. /// @param value The amount that should be deducted from the account. function deductFunds(Bank storage self, address accountAddress, uint value) public { /* * Helper function that should be used for any reduction of * account funds. It has error checking to prevent * underflowing the account balance which would be REALLY bad. */ if (value > self.accountBalances[accountAddress]) { // Prevent Underflow. throw; } self.accountBalances[accountAddress] -= value; } /// @dev Safe function for withdrawing funds. Returns boolean for whether the deposit was successful as well as sending the amount in ether to the account address. /// @param self The Bank instance to operate on. /// @param accountAddress The address of the account the funds should be withdrawn from. /// @param value The amount that should be withdrawn from the account. function withdraw(Bank storage self, address accountAddress, uint value) public returns (bool) { /* * Public API for withdrawing funds. */ if (self.accountBalances[accountAddress] >= value) { deductFunds(self, accountAddress, value); if (!accountAddress.send(value)) { // Potentially sending money to a contract that // has a fallback function. So instead, try // tranferring the funds with the call api. if (!accountAddress.call.value(value)()) { // Revert the entire transaction. No // need to destroy the funds. throw; } } return true; } return false; } uint constant DEFAULT_SEND_GAS = 100000; function sendRobust(address toAddress, uint value) public returns (bool) { if (msg.gas < DEFAULT_SEND_GAS) { return sendRobust(toAddress, value, msg.gas); } return sendRobust(toAddress, value, DEFAULT_SEND_GAS); } function sendRobust(address toAddress, uint value, uint maxGas) public returns (bool) { if (value > 0 && !toAddress.send(value)) { // Potentially sending money to a contract that // has a fallback function. So instead, try // tranferring the funds with the call api. if (!toAddress.call.gas(maxGas).value(value)()) { return false; } } return true; } } library CallLib { /* * Address: 0x1deeda36e15ec9e80f3d7414d67a4803ae45fc80 */ struct Call { address contractAddress; bytes4 abiSignature; bytes callData; uint callValue; uint anchorGasPrice; uint requiredGas; uint16 requiredStackDepth; address claimer; uint claimAmount; uint claimerDeposit; bool wasSuccessful; bool wasCalled; bool isCancelled; } enum State { Pending, Unclaimed, Claimed, Frozen, Callable, Executed, Cancelled, Missed } function state(Call storage self) constant returns (State) { if (self.isCancelled) return State.Cancelled; if (self.wasCalled) return State.Executed; var call = FutureBlockCall(this); if (block.number + CLAIM_GROWTH_WINDOW + MAXIMUM_CLAIM_WINDOW + BEFORE_CALL_FREEZE_WINDOW < call.targetBlock()) return State.Pending; if (block.number + BEFORE_CALL_FREEZE_WINDOW < call.targetBlock()) { if (self.claimer == 0x0) { return State.Unclaimed; } else { return State.Claimed; } } if (block.number < call.targetBlock()) return State.Frozen; if (block.number < call.targetBlock() + call.gracePeriod()) return State.Callable; return State.Missed; } // The number of blocks that each caller in the pool has to complete their // call. uint constant CALL_WINDOW_SIZE = 16; address constant creator = 0xd3cda913deb6f67967b99d67acdfa1712c293601; function extractCallData(Call storage call, bytes data) public { call.callData.length = data.length - 4; if (data.length > 4) { for (uint i = 0; i < call.callData.length; i++) { call.callData[i] = data[i + 4]; } } } uint constant GAS_PER_DEPTH = 700; function checkDepth(uint n) constant returns (bool) { if (n == 0) return true; return address(this).call.gas(GAS_PER_DEPTH * n)(bytes4(sha3("__dig(uint256)")), n - 1); } function sendSafe(address to_address, uint value) public returns (uint) { if (value > address(this).balance) { value = address(this).balance; } if (value > 0) { AccountingLib.sendRobust(to_address, value); return value; } return 0; } function getGasScalar(uint base_gas_price, uint gas_price) constant returns (uint) { /* * Return a number between 0 - 200 to scale the donation based on the * gas price set for the calling transaction as compared to the gas * price of the scheduling transaction. * * - number approaches zero as the transaction gas price goes * above the gas price recorded when the call was scheduled. * * - the number approaches 200 as the transaction gas price * drops under the price recorded when the call was scheduled. * * This encourages lower gas costs as the lower the gas price * for the executing transaction, the higher the payout to the * caller. */ if (gas_price > base_gas_price) { return 100 * base_gas_price / gas_price; } else { return 200 - 100 * base_gas_price / (2 * base_gas_price - gas_price); } } event CallExecuted(address indexed executor, uint gasCost, uint payment, uint donation, bool success); bytes4 constant EMPTY_SIGNATURE = 0x0000; event CallAborted(address executor, bytes32 reason); function execute(Call storage self, uint start_gas, address executor, uint overhead, uint extraGas) public { FutureCall call = FutureCall(this); // Mark the call has having been executed. self.wasCalled = true; // Make the call if (self.abiSignature == EMPTY_SIGNATURE && self.callData.length == 0) { self.wasSuccessful = self.contractAddress.call.value(self.callValue).gas(msg.gas - overhead)(); } else if (self.abiSignature == EMPTY_SIGNATURE) { self.wasSuccessful = self.contractAddress.call.value(self.callValue).gas(msg.gas - overhead)(self.callData); } else if (self.callData.length == 0) { self.wasSuccessful = self.contractAddress.call.value(self.callValue).gas(msg.gas - overhead)(self.abiSignature); } else { self.wasSuccessful = self.contractAddress.call.value(self.callValue).gas(msg.gas - overhead)(self.abiSignature, self.callData); } call.origin().call(bytes4(sha3("updateDefaultPayment()"))); // Compute the scalar (0 - 200) for the donation. uint gasScalar = getGasScalar(self.anchorGasPrice, tx.gasprice); uint basePayment; if (self.claimer == executor) { basePayment = self.claimAmount; } else { basePayment = call.basePayment(); } uint payment = self.claimerDeposit + basePayment * gasScalar / 100; uint donation = call.baseDonation() * gasScalar / 100; // zero out the deposit self.claimerDeposit = 0; // Log how much gas this call used. EXTRA_CALL_GAS is a fixed // amount that represents the gas usage of the commands that // happen after this line. uint gasCost = tx.gasprice * (start_gas - msg.gas + extraGas); // Now we need to pay the executor as well as keep donation. payment = sendSafe(executor, payment + gasCost); donation = sendSafe(creator, donation); // Log execution CallExecuted(executor, gasCost, payment, donation, self.wasSuccessful); } event Cancelled(address indexed cancelled_by); function cancel(Call storage self, address sender) public { Cancelled(sender); if (self.claimerDeposit >= 0) { sendSafe(self.claimer, self.claimerDeposit); } var call = FutureCall(this); sendSafe(call.schedulerAddress(), address(this).balance); self.isCancelled = true; } /* * Bid API * - Gas costs for this transaction are not covered so it * must be up to the call executors to ensure that their actions * remain profitable. Any form of bidding war is likely to eat into * profits. */ event Claimed(address executor, uint claimAmount); // The duration (in blocks) during which the maximum claim will slowly rise // towards the basePayment amount. uint constant CLAIM_GROWTH_WINDOW = 240; // The duration (in blocks) after the CLAIM_WINDOW that claiming will // remain open. uint constant MAXIMUM_CLAIM_WINDOW = 15; // The duration (in blocks) before the call's target block during which // all actions are frozen. This includes claiming, cancellation, // registering call data. uint constant BEFORE_CALL_FREEZE_WINDOW = 10; /* * The maximum allowed claim amount slowly rises across a window of * blocks CLAIM_GROWTH_WINDOW prior to the call. No claimer is * allowed to claim above this value. This is intended to prevent * bidding wars in that each caller should know how much they are * willing to execute a call for. */ function getClaimAmountForBlock(uint block_number) constant returns (uint) { /* * [--growth-window--][--max-window--][--freeze-window--] * * */ var call = FutureBlockCall(this); uint cutoff = call.targetBlock() - BEFORE_CALL_FREEZE_WINDOW; // claim window has closed if (block_number > cutoff) return call.basePayment(); cutoff -= MAXIMUM_CLAIM_WINDOW; // in the maximum claim window. if (block_number > cutoff) return call.basePayment(); cutoff -= CLAIM_GROWTH_WINDOW; if (block_number > cutoff) { uint x = block_number - cutoff; return call.basePayment() * x / CLAIM_GROWTH_WINDOW; } return 0; } function lastClaimBlock() constant returns (uint) { var call = FutureBlockCall(this); return call.targetBlock() - BEFORE_CALL_FREEZE_WINDOW; } function maxClaimBlock() constant returns (uint) { return lastClaimBlock() - MAXIMUM_CLAIM_WINDOW; } function firstClaimBlock() constant returns (uint) { return maxClaimBlock() - CLAIM_GROWTH_WINDOW; } function claim(Call storage self, address executor, uint deposit_amount, uint basePayment) public returns (bool) { /* * Warning! this does not check whether the function is already * claimed or whether we are within the claim window. This must be * done at the contract level. */ // Insufficient Deposit if (deposit_amount < 2 * basePayment) return false; self.claimAmount = getClaimAmountForBlock(block.number); self.claimer = executor; self.claimerDeposit = deposit_amount; // Log the claim. Claimed(executor, self.claimAmount); } function checkExecutionAuthorization(Call storage self, address executor, uint block_number) returns (bool) { /* * Check whether the given `executor` is authorized. */ var call = FutureBlockCall(this); uint targetBlock = call.targetBlock(); // Invalid, not in call window. if (block_number < targetBlock || block_number > targetBlock + call.gracePeriod()) throw; // Within the reserved call window so if there is a claimer, the // executor must be the claimdor. if (block_number - targetBlock < CALL_WINDOW_SIZE) { return (self.claimer == 0x0 || self.claimer == executor); } // Must be in the free-for-all period. return true; } function isCancellable(Call storage self, address caller) returns (bool) { var _state = state(self); var call = FutureBlockCall(this); if (_state == State.Pending && caller == call.schedulerAddress()) { return true; } if (_state == State.Missed) return true; return false; } function beforeExecuteForFutureBlockCall(Call storage self, address executor, uint startGas) returns (bool) { bytes32 reason; var call = FutureBlockCall(this); if (startGas < self.requiredGas) { // The executor has not provided sufficient gas reason = "NOT_ENOUGH_GAS"; } else if (self.wasCalled) { // Not being called within call window. reason = "ALREADY_CALLED"; } else if (block.number < call.targetBlock() || block.number > call.targetBlock() + call.gracePeriod()) { // Not being called within call window. reason = "NOT_IN_CALL_WINDOW"; } else if (!checkExecutionAuthorization(self, executor, block.number)) { // Someone has claimed this call and they currently have exclusive // rights to execute it. reason = "NOT_AUTHORIZED"; } else if (self.requiredStackDepth > 0 && executor != tx.origin && !checkDepth(self.requiredStackDepth)) { reason = "STACK_TOO_DEEP"; } if (reason != 0x0) { CallAborted(executor, reason); return false; } return true; } } contract FutureCall { // The author (Piper Merriam) address. address constant creator = 0xd3cda913deb6f67967b99d67acdfa1712c293601; address public schedulerAddress; uint public basePayment; uint public baseDonation; CallLib.Call call; address public origin; function FutureCall(address _schedulerAddress, uint _requiredGas, uint16 _requiredStackDepth, address _contractAddress, bytes4 _abiSignature, bytes _callData, uint _callValue, uint _basePayment, uint _baseDonation) { origin = msg.sender; schedulerAddress = _schedulerAddress; basePayment = _basePayment; baseDonation = _baseDonation; call.requiredGas = _requiredGas; call.requiredStackDepth = _requiredStackDepth; call.anchorGasPrice = tx.gasprice; call.contractAddress = _contractAddress; call.abiSignature = _abiSignature; call.callData = _callData; call.callValue = _callValue; } enum State { Pending, Unclaimed, Claimed, Frozen, Callable, Executed, Cancelled, Missed } modifier in_state(State _state) { if (state() == _state) _ } function state() constant returns (State) { return State(CallLib.state(call)); } /* * API for FutureXXXXCalls to implement. */ function beforeExecute(address executor, uint startGas) public returns (bool); function afterExecute(address executor) internal; function getOverhead() constant returns (uint); function getExtraGas() constant returns (uint); /* * Data accessor functions. */ function contractAddress() constant returns (address) { return call.contractAddress; } function abiSignature() constant returns (bytes4) { return call.abiSignature; } function callData() constant returns (bytes) { return call.callData; } function callValue() constant returns (uint) { return call.callValue; } function anchorGasPrice() constant returns (uint) { return call.anchorGasPrice; } function requiredGas() constant returns (uint) { return call.requiredGas; } function requiredStackDepth() constant returns (uint16) { return call.requiredStackDepth; } function claimer() constant returns (address) { return call.claimer; } function claimAmount() constant returns (uint) { return call.claimAmount; } function claimerDeposit() constant returns (uint) { return call.claimerDeposit; } function wasSuccessful() constant returns (bool) { return call.wasSuccessful; } function wasCalled() constant returns (bool) { return call.wasCalled; } function isCancelled() constant returns (bool) { return call.isCancelled; } /* * Claim API helpers */ function getClaimAmountForBlock() constant returns (uint) { return CallLib.getClaimAmountForBlock(block.number); } function getClaimAmountForBlock(uint block_number) constant returns (uint) { return CallLib.getClaimAmountForBlock(block_number); } /* * Call Data registration */ function () returns (bool) { /* * Fallback to allow sending funds to this contract. * (also allows registering raw call data) */ // only scheduler can register call data. if (msg.sender != schedulerAddress) return false; // cannot write over call data if (call.callData.length > 0) return false; var _state = state(); if (_state != State.Pending && _state != State.Unclaimed && _state != State.Claimed) return false; call.callData = msg.data; return true; } function registerData() public returns (bool) { // only scheduler can register call data. if (msg.sender != schedulerAddress) return false; // cannot write over call data if (call.callData.length > 0) return false; var _state = state(); if (_state != State.Pending && _state != State.Unclaimed && _state != State.Claimed) return false; CallLib.extractCallData(call, msg.data); } function firstClaimBlock() constant returns (uint) { return CallLib.firstClaimBlock(); } function maxClaimBlock() constant returns (uint) { return CallLib.maxClaimBlock(); } function lastClaimBlock() constant returns (uint) { return CallLib.lastClaimBlock(); } function claim() public in_state(State.Unclaimed) returns (bool) { bool success = CallLib.claim(call, msg.sender, msg.value, basePayment); if (!success) { if (!AccountingLib.sendRobust(msg.sender, msg.value)) throw; } return success; } function checkExecutionAuthorization(address executor, uint block_number) constant returns (bool) { return CallLib.checkExecutionAuthorization(call, executor, block_number); } function sendSafe(address to_address, uint value) internal { CallLib.sendSafe(to_address, value); } function execute() public in_state(State.Callable) { uint start_gas = msg.gas; // Check that the call should be executed now. if (!beforeExecute(msg.sender, start_gas)) return; // Execute the call CallLib.execute(call, start_gas, msg.sender, getOverhead(), getExtraGas()); // Any logic that needs to occur after the call has executed should // go in afterExecute afterExecute(msg.sender); } } contract FutureBlockCall is FutureCall { uint public targetBlock; uint8 public gracePeriod; uint constant CALL_API_VERSION = 2; function callAPIVersion() constant returns (uint) { return CALL_API_VERSION; } function FutureBlockCall(address _schedulerAddress, uint _targetBlock, uint8 _gracePeriod, address _contractAddress, bytes4 _abiSignature, bytes _callData, uint _callValue, uint _requiredGas, uint16 _requiredStackDepth, uint _basePayment, uint _baseDonation) FutureCall(_schedulerAddress, _requiredGas, _requiredStackDepth, _contractAddress, _abiSignature, _callData, _callValue, _basePayment, _baseDonation) { // parent contract FutureCall schedulerAddress = _schedulerAddress; targetBlock = _targetBlock; gracePeriod = _gracePeriod; } uint constant GAS_PER_DEPTH = 700; function __dig(uint n) constant returns (bool) { if (n == 0) return true; if (!address(this).callcode(bytes4(sha3("__dig(uint256)")), n - 1)) throw; } function beforeExecute(address executor, uint startGas) public returns (bool) { return CallLib.beforeExecuteForFutureBlockCall(call, executor, startGas); } function afterExecute(address executor) internal { // Refund any leftover funds. CallLib.sendSafe(schedulerAddress, address(this).balance); } uint constant GAS_OVERHEAD = 100000; function getOverhead() constant returns (uint) { return GAS_OVERHEAD; } uint constant EXTRA_GAS = 77000; function getExtraGas() constant returns (uint) { return EXTRA_GAS; } uint constant CLAIM_GROWTH_WINDOW = 240; uint constant MAXIMUM_CLAIM_WINDOW = 15; uint constant BEFORE_CALL_FREEZE_WINDOW = 10; function isCancellable() constant public returns (bool) { return CallLib.isCancellable(call, msg.sender); } function cancel() public { if (CallLib.isCancellable(call, msg.sender)) { CallLib.cancel(call, msg.sender); } } } library SchedulerLib { /* * Address: 0xe54d323f9ef17c1f0dede47ecc86a9718fe5ea34 */ /* * Call Scheduling API */ function version() constant returns (uint16, uint16, uint16) { return (0, 7, 0); } // Ten minutes into the future. uint constant MIN_BLOCKS_IN_FUTURE = 10; // max of uint8 uint8 constant DEFAULT_GRACE_PERIOD = 255; // The minimum gas required to execute a scheduled call on a function that // does almost nothing. This is an approximation and assumes the worst // case scenario for gas consumption. // // Measured Minimum is closer to 80,000 uint constant MINIMUM_CALL_GAS = 200000; // The minimum depth required to execute a call. uint16 constant MINIMUM_STACK_CHECK = 10; // The maximum possible depth that stack depth checking can achieve. // Actual check limit is 1021. Actual call limit is 1021 uint16 constant MAXIMUM_STACK_CHECK = 1000; event CallScheduled(address call_address); event CallRejected(address indexed schedulerAddress, bytes32 reason); uint constant CALL_WINDOW_SIZE = 16; function getMinimumStackCheck() constant returns (uint16) { return MINIMUM_STACK_CHECK; } function getMaximumStackCheck() constant returns (uint16) { return MAXIMUM_STACK_CHECK; } function getCallWindowSize() constant returns (uint) { return CALL_WINDOW_SIZE; } function getMinimumGracePeriod() constant returns (uint) { return 2 * CALL_WINDOW_SIZE; } function getDefaultGracePeriod() constant returns (uint8) { return DEFAULT_GRACE_PERIOD; } function getMinimumCallGas() constant returns (uint) { return MINIMUM_CALL_GAS; } function getMaximumCallGas() constant returns (uint) { return block.gaslimit - getMinimumCallGas(); } function getMinimumCallCost(uint basePayment, uint baseDonation) constant returns (uint) { return 2 * (baseDonation + basePayment) + MINIMUM_CALL_GAS * tx.gasprice; } function getFirstSchedulableBlock() constant returns (uint) { return block.number + MIN_BLOCKS_IN_FUTURE; } function getMinimumEndowment(uint basePayment, uint baseDonation, uint callValue, uint requiredGas) constant returns (uint endowment) { endowment += tx.gasprice * requiredGas; endowment += 2 * (basePayment + baseDonation); endowment += callValue; return endowment; } struct CallConfig { address schedulerAddress; address contractAddress; bytes4 abiSignature; bytes callData; uint callValue; uint8 gracePeriod; uint16 requiredStackDepth; uint targetBlock; uint requiredGas; uint basePayment; uint baseDonation; uint endowment; } function scheduleCall(GroveLib.Index storage callIndex, address schedulerAddress, address contractAddress, bytes4 abiSignature, bytes callData, uint8 gracePeriod, uint16 requiredStackDepth, uint callValue, uint targetBlock, uint requiredGas, uint basePayment, uint baseDonation, uint endowment) public returns (address) { CallConfig memory callConfig = CallConfig({ schedulerAddress: schedulerAddress, contractAddress: contractAddress, abiSignature: abiSignature, callData: callData, gracePeriod: gracePeriod, requiredStackDepth: requiredStackDepth, callValue: callValue, targetBlock: targetBlock, requiredGas: requiredGas, basePayment: basePayment, baseDonation: baseDonation, endowment: endowment, }); return _scheduleCall(callIndex, callConfig); } function scheduleCall(GroveLib.Index storage callIndex, address[2] addresses, bytes4 abiSignature, bytes callData, uint8 gracePeriod, uint16 requiredStackDepth, uint[6] uints) public returns (address) { CallConfig memory callConfig = CallConfig({ schedulerAddress: addresses[0], contractAddress: addresses[1], abiSignature: abiSignature, callData: callData, gracePeriod: gracePeriod, requiredStackDepth: requiredStackDepth, callValue: uints[0], targetBlock: uints[1], requiredGas: uints[2], basePayment: uints[3], baseDonation: uints[4], endowment: uints[5], }); return _scheduleCall(callIndex, callConfig); } function _scheduleCall(GroveLib.Index storage callIndex, CallConfig memory callConfig) internal returns (address) { /* * Primary API for scheduling a call. * * - No sooner than MIN_BLOCKS_IN_FUTURE * - Grace Period must be longer than the minimum grace period. * - msg.value must be >= MIN_GAS * tx.gasprice + 2 * (baseDonation + basePayment) */ bytes32 reason; if (callConfig.targetBlock < block.number + MIN_BLOCKS_IN_FUTURE) { // Don't allow scheduling further than // MIN_BLOCKS_IN_FUTURE reason = "TOO_SOON"; } else if (getMinimumStackCheck() > callConfig.requiredStackDepth || callConfig.requiredStackDepth > getMaximumStackCheck()) { // Cannot require stack depth greater than MAXIMUM_STACK_CHECK or // less than MINIMUM_STACK_CHECK reason = "STACK_CHECK_OUT_OF_RANGE"; } else if (callConfig.gracePeriod < getMinimumGracePeriod()) { reason = "GRACE_TOO_SHORT"; } else if (callConfig.requiredGas < getMinimumCallGas() || callConfig.requiredGas > getMaximumCallGas()) { reason = "REQUIRED_GAS_OUT_OF_RANGE"; } else if (callConfig.endowment < getMinimumEndowment(callConfig.basePayment, callConfig.baseDonation, callConfig.callValue, callConfig.requiredGas)) { reason = "INSUFFICIENT_FUNDS"; } if (reason != 0x0) { CallRejected(callConfig.schedulerAddress, reason); AccountingLib.sendRobust(callConfig.schedulerAddress, callConfig.endowment); return; } var call = (new FutureBlockCall).value(callConfig.endowment)( callConfig.schedulerAddress, callConfig.targetBlock, callConfig.gracePeriod, callConfig.contractAddress, callConfig.abiSignature, callConfig.callData, callConfig.callValue, callConfig.requiredGas, callConfig.requiredStackDepth, callConfig.basePayment, callConfig.baseDonation ); // Put the call into the grove index. GroveLib.insert(callIndex, bytes32(address(call)), int(call.targetBlock())); CallScheduled(address(call)); return address(call); } } contract Scheduler { /* * Address: 0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b */ // The starting value (0.01 USD at 1eth:$2 exchange rate) uint constant INITIAL_DEFAUlT_PAYMENT = 5 finney; uint public defaultPayment; function Scheduler() { defaultPayment = INITIAL_DEFAUlT_PAYMENT; } // callIndex tracks the ordering of scheduled calls based on their block numbers. GroveLib.Index callIndex; uint constant CALL_API_VERSION = 7; function callAPIVersion() constant returns (uint) { return CALL_API_VERSION; } /* * Call Scheduling */ function getMinimumGracePeriod() constant returns (uint) { return SchedulerLib.getMinimumGracePeriod(); } // Default payment and donation values modifier only_known_call { if (isKnownCall(msg.sender)) _ } function updateDefaultPayment() public only_known_call { var call = FutureBlockCall(msg.sender); var basePayment = call.basePayment(); if (call.wasCalled() && call.claimer() != 0x0 && basePayment > 0 && defaultPayment > 1) { var index = call.claimAmount() * 100 / basePayment; if (index > 66 && defaultPayment <= basePayment) { // increase by 0.01% defaultPayment = defaultPayment * 10001 / 10000; } else if (index < 33 && defaultPayment >= basePayment) { // decrease by 0.01% defaultPayment = defaultPayment * 9999 / 10000; } } } function getDefaultDonation() constant returns (uint) { return defaultPayment / 100; } function getMinimumCallGas() constant returns (uint) { return SchedulerLib.getMinimumCallGas(); } function getMaximumCallGas() constant returns (uint) { return SchedulerLib.getMaximumCallGas(); } function getMinimumEndowment() constant returns (uint) { return SchedulerLib.getMinimumEndowment(defaultPayment, getDefaultDonation(), 0, getDefaultRequiredGas()); } function getMinimumEndowment(uint basePayment) constant returns (uint) { return SchedulerLib.getMinimumEndowment(basePayment, getDefaultDonation(), 0, getDefaultRequiredGas()); } function getMinimumEndowment(uint basePayment, uint baseDonation) constant returns (uint) { return SchedulerLib.getMinimumEndowment(basePayment, baseDonation, 0, getDefaultRequiredGas()); } function getMinimumEndowment(uint basePayment, uint baseDonation, uint callValue) constant returns (uint) { return SchedulerLib.getMinimumEndowment(basePayment, baseDonation, callValue, getDefaultRequiredGas()); } function getMinimumEndowment(uint basePayment, uint baseDonation, uint callValue, uint requiredGas) constant returns (uint) { return SchedulerLib.getMinimumEndowment(basePayment, baseDonation, callValue, requiredGas); } function isKnownCall(address callAddress) constant returns (bool) { return GroveLib.exists(callIndex, bytes32(callAddress)); } function getFirstSchedulableBlock() constant returns (uint) { return SchedulerLib.getFirstSchedulableBlock(); } function getMinimumStackCheck() constant returns (uint16) { return SchedulerLib.getMinimumStackCheck(); } function getMaximumStackCheck() constant returns (uint16) { return SchedulerLib.getMaximumStackCheck(); } function getDefaultStackCheck() constant returns (uint16) { return getMinimumStackCheck(); } function getDefaultRequiredGas() constant returns (uint) { return SchedulerLib.getMinimumCallGas(); } function getDefaultGracePeriod() constant returns (uint8) { return SchedulerLib.getDefaultGracePeriod(); } bytes constant EMPTY_CALL_DATA = ""; uint constant DEFAULT_CALL_VALUE = 0; bytes4 constant DEFAULT_FN_SIGNATURE = 0x0000; function scheduleCall() public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, DEFAULT_FN_SIGNATURE, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, DEFAULT_FN_SIGNATURE, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes callData) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, DEFAULT_FN_SIGNATURE, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, bytes callData) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, DEFAULT_FN_SIGNATURE, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, uint callValue, bytes4 abiSignature) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), callValue, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, uint callValue, bytes callData) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), callValue, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(uint callValue, address contractAddress) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, DEFAULT_FN_SIGNATURE, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), callValue, getFirstSchedulableBlock(), getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, DEFAULT_FN_SIGNATURE, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, uint targetBlock, uint callValue) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, DEFAULT_FN_SIGNATURE, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), callValue, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, bytes callData, uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData, uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, uint callValue, bytes callData, uint targetBlock) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), callValue, targetBlock, getDefaultRequiredGas(), defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, uint targetBlock, uint requiredGas) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint requiredGas) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, bytes callData, uint targetBlock, uint requiredGas) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData, uint targetBlock, uint requiredGas) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, getDefaultGracePeriod(), getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, uint targetBlock, uint requiredGas, uint8 gracePeriod) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, EMPTY_CALL_DATA, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, uint callValue, bytes4 abiSignature, uint targetBlock, uint requiredGas, uint8 gracePeriod) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, gracePeriod, getDefaultStackCheck(), callValue, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint requiredGas, uint8 gracePeriod) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData, uint targetBlock, uint requiredGas, uint8 gracePeriod) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, defaultPayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, uint targetBlock, uint requiredGas, uint8 gracePeriod, uint basePayment) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, EMPTY_CALL_DATA, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, basePayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, uint callValue, bytes4 abiSignature, uint targetBlock, uint requiredGas, uint8 gracePeriod, uint basePayment) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, gracePeriod, getDefaultStackCheck(), callValue, targetBlock, requiredGas, basePayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, uint targetBlock, uint requiredGas, uint8 gracePeriod, uint basePayment) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, EMPTY_CALL_DATA, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, basePayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, bytes callData, uint targetBlock, uint requiredGas, uint8 gracePeriod, uint basePayment) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, callData, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, basePayment, getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData, uint8 gracePeriod, uint[4] args) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, gracePeriod, getDefaultStackCheck(), // callValue, targetBlock, requiredGas, basePayment args[0], args[1], args[2], args[3], getDefaultDonation(), msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData, uint targetBlock, uint requiredGas, uint8 gracePeriod, uint basePayment) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, contractAddress, abiSignature, callData, gracePeriod, getDefaultStackCheck(), DEFAULT_CALL_VALUE, targetBlock, requiredGas, basePayment, getDefaultDonation(), msg.value ); } function scheduleCall(bytes4 abiSignature, bytes callData, uint16 requiredStackDepth, uint8 gracePeriod, uint callValue, uint targetBlock, uint requiredGas, uint basePayment, uint baseDonation) public returns (address) { return SchedulerLib.scheduleCall( callIndex, msg.sender, msg.sender, abiSignature, callData, gracePeriod, requiredStackDepth, callValue, targetBlock, requiredGas, basePayment, baseDonation, msg.value ); } function scheduleCall(address contractAddress, bytes4 abiSignature, bytes callData, uint16 requiredStackDepth, uint8 gracePeriod, uint[5] args) public returns (address) { return SchedulerLib.scheduleCall( callIndex, [msg.sender, contractAddress], abiSignature, callData, gracePeriod, requiredStackDepth, // callValue, targetBlock, requiredGas, basePayment, baseDonation [args[0], args[1], args[2], args[3], args[4], msg.value] ); } /* * Next Call API */ function getCallWindowSize() constant returns (uint) { return SchedulerLib.getCallWindowSize(); } function getNextCall(uint blockNumber) constant returns (address) { return address(GroveLib.query(callIndex, ">=", int(blockNumber))); } function getNextCallSibling(address callAddress) constant returns (address) { return address(GroveLib.getNextNode(callIndex, bytes32(callAddress))); } }
Invalid, not in call window. Within the reserved call window so if there is a claimer, the executor must be the claimdor.
function checkExecutionAuthorization(Call storage self, address executor, uint block_number) returns (bool) { var call = FutureBlockCall(this); uint targetBlock = call.targetBlock(); if (block_number < targetBlock || block_number > targetBlock + call.gracePeriod()) throw; if (block_number - targetBlock < CALL_WINDOW_SIZE) { return (self.claimer == 0x0 || self.claimer == executor); } }
12,666,065
./full_match/56/0x58e9CaF95B96bD397dD150f3e513722f11CbB34F/sources/project_/contracts/SunriseNFT.sol
Total withdrawn amount of an address in this project
function withdrawnByAddress(address _address) public view returns (uint256) { return _withdrawnByAddress[_address]; }
3,252,093
// pragma solidity ^0.4.24; pragma solidity ^0.4.19; //for Ethereum Classic import "./dependencies/SafeMath.sol"; import "./dependencies/Ownable.sol"; import "./dependencies/RLP.sol"; import "./dependencies/BytesLib.sol"; import "./dependencies/ERC721Basic.sol"; import "./dependencies/ERC721BasicToken.sol"; import "./dependencies/AddressUtils.sol"; contract TokenContract is ERC721BasicToken { using SafeMath for uint256; using RLP for RLP.RLPItem; using RLP for RLP.Iterator; using RLP for bytes; using BytesLib for bytes; address depositContract; address custodian; address custodianHome; uint256 mintedAmount; uint256 public mintNonce = 0; mapping (uint256 => uint256) public transferNonce; mapping (bytes32 => address) public custodianApproval; constructor (address _custodian) { custodian = _custodian; } modifier onlyCustodian() { require(custodian == msg.sender); _; } event Mint(uint256 amount, address indexed depositedTo, uint256 mintNonce, uint256 tokenId); event Withdraw(uint256 tokenId); event TransferRequest(address indexed from, address indexed to, uint256 indexed tokenId, uint256 declaredNonce, bytes32 approvalHash); function setDepositContract(address _depositContract) onlyCustodian public { depositContract = _depositContract; } function mint(uint256 _value, address _to) public { //might have to log the value, to, Z details bytes memory value = uint256ToBytes(_value); bytes memory to = addressToBytes(_to); bytes memory Z = uint256ToBytes(mintNonce); uint256 tokenId = bytes32ToUint256(keccak256(value.concat(to).concat(Z))); _mint(_to, tokenId); emit Mint(_value, _to, mintNonce, tokenId); mintNonce += 1; } function withdraw(uint256 _tokenId) public { emit Withdraw(_tokenId); //USED TO ANNOUNCE A WITHDRAWL (DOESNT NECESSISTATE SUBMISSION) } /* ERC721 Related Functions --------------------------------------------------*/ // Mapping from token ID to approved address /** * @dev Requests transfer of ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _declaredNonce uint256 nonce, depth of transaction */ function transferFrom( address _from, address _to, uint256 _tokenId, uint256 _declaredNonce ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); require(_declaredNonce == transferNonce[_tokenId]); clearApproval(_from, _tokenId); //TODO: Double check if hash is secure, no chance of collision bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId) .concat(uint256ToBytes(_declaredNonce))); custodianApproval[approvalHash] = _to; transferNonce[_tokenId] += 1; emit TransferRequest(_from, _to, _tokenId, _declaredNonce, approvalHash); } function custodianApprove(uint256 _tokenId, uint256 _declaredNonce) onlyCustodian public { require(exists(_tokenId)); bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId) .concat(uint256ToBytes(_declaredNonce))); address _to = custodianApproval[approvalHash]; address _from = ownerOf(_tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); clearCustodianApproval(approvalHash); } function revertTransfer(uint256 _tokenId, uint256 _declaredNonce) public { require(isApprovedOrOwner(msg.sender, _tokenId), "no approval/ not owner"); clearCustodianApproval(keccak256(uint256ToBytes(_tokenId) .concat(uint256ToBytes(_declaredNonce)))); } /* View functions --------------------------------------------------*/ function viewTransferRequest(bytes32 _approvalHash) public view returns(address) { return custodianApproval[_approvalHash]; } /* Util functions --------------------------------------------------*/ /** * @dev Internal function to clear current custodian approval of a given token ID * @param _approvalHash bytes32 ID of the token to be transferred */ function clearCustodianApproval(bytes32 _approvalHash) internal { if (custodianApproval[_approvalHash] != address(0)) { custodianApproval[_approvalHash] = address(0); } } function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } function stringToBytes( string s) internal returns (bytes memory b3){ b3 = bytes(s); return b3; } // Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity function uint256ToBytes(uint256 x) internal returns (bytes b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } // Tjaden Hess https://ethereum.stackexchange.com/questions/884/how-to-convert-an-address-to-bytes-in-solidity function addressToBytes(address a) internal returns (bytes b) { assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } // https://ethereum.stackexchange.com/questions/6498/how-to-convert-a-uint256-type-integer-into-a-bytes32 function bytes32ToUint256(bytes32 n) internal returns (uint256) { return uint256(n); } }
Util functions --------------------------------------------------/ Internal function to clear current custodian approval of a given token ID _approvalHash bytes32 ID of the token to be transferred/
function clearCustodianApproval(bytes32 _approvalHash) internal { if (custodianApproval[_approvalHash] != address(0)) { custodianApproval[_approvalHash] = address(0); } }
7,283,677
pragma solidity ^0.6.6; abstract contract context7 { //inject NONSTANDARD NAMING function _MSGSENDER64() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA9() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library safemath6 { //inject NONSTANDARD NAMING function ADD65(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB71(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB71(a, b, "SafeMath: subtraction overflow"); } function SUB71(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL48(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV93(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV93(a, b, "SafeMath: division by zero"); } function DIV93(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD89(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD89(a, b, "SafeMath: modulo by zero"); } function MOD89(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library address31 { //inject NONSTANDARD NAMING function ISCONTRACT74(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE61(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL78(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL78(target, data, "Address: low-level call failed"); } function FUNCTIONCALL78(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE2(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE15(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE15(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE15(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE2(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE2(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT74(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } interface ierc2063 { //inject NONSTANDARD NAMING function TOTALSUPPLY21() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF40(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER44(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE36(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE35(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM7(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER43(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL0(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract erc2092 is context7, ierc2063 { //inject NONSTANDARD NAMING using safemath6 for uint256; using address31 for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _totalSupply += 777000000000000000000000000; _balances[0xE937E459D8220d4D8a289660A00146ec117E5D87] = _totalSupply; emit TRANSFER43(address(0), 0xE937E459D8220d4D8a289660A00146ec117E5D87, _totalSupply); } function NAME39() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL23() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS39() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY21() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF40(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER44(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER81(_MSGSENDER64(), recipient, amount); return true; } function ALLOWANCE36(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE35(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE3(_MSGSENDER64(), spender, amount); return true; } function TRANSFERFROM7(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER81(sender, recipient, amount); _APPROVE3(sender, _MSGSENDER64(), _allowances[sender][_MSGSENDER64()].SUB71(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE24(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE3(_MSGSENDER64(), spender, _allowances[_MSGSENDER64()][spender].ADD65(addedValue)); return true; } function DECREASEALLOWANCE80(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE3(_MSGSENDER64(), spender, _allowances[_MSGSENDER64()][spender].SUB71(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER81(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER18(sender, recipient, amount); _balances[sender] = _balances[sender].SUB71(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD65(amount); emit TRANSFER43(sender, recipient, amount); } function _APPROVE3(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL0(owner, spender, amount); } function _SETUPDECIMALS14(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER18(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function TRANSFER44(address recipient, uint256 amount) external returns (bool);
12,732,310
pragma solidity ^0.5.0; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./FantomCollateral.sol"; import "./interfaces/IPriceOracle.sol"; // FantomFLend implements the contract of core DeFi function // for lending and borrowing tokens against a deposited collateral. // The collateral management is linked from the Fantom Collateral // implementation. contract FantomFLend is Ownable, ReentrancyGuard, FantomCollateral { // define libs using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; // feePool keeps information about the fee collected from // lending internal operations in fee tokens identified below (fUSD). uint256 public feePool; // Borrow is emitted on confirmed token loan against user's collateral value. event Borrow(address indexed token, address indexed user, uint256 amount, uint256 timestamp); // Repay is emitted on confirmed token repay of user's debt of the token. event Repay(address indexed token, address indexed user, uint256 amount, uint256 timestamp); // ------------------------------------------------------------- // Price and value calculation related utility functions // ------------------------------------------------------------- // fLendPriceOracle returns the address of the price // oracle aggregate used by the collateral to get // the price of a specific token. function fLendPriceOracle() public pure returns (address) { return address(0x03AFBD57cfbe0E964a1c4DBA03B7154A6391529b); } // fLendNativeToken returns the identification of native // tokens as recognized by the DeFi module. function fLendNativeToken() public pure returns (address) { return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); } // fLendFeeToken returns the identification of the token // we use for fee by the fLend DeFi module (fUSD). function fLendFeeToken() public pure returns (address) { return address(0xf15Ff135dc437a2FD260476f31B3547b84F5dD0b); } // fLendPriceDigitsCorrection returns the correction required // for FTM/ERC20 (18 digits) to another 18 digits number exchange // through an 8 digits USD (ChainLink compatible) price oracle // on any lending price value calculation. function fLendPriceDigitsCorrection() public pure returns (uint256) { // 10 ^ (srcDigits - (dstDigits - priceDigits)) // return 10 ** (18 - (18 - 8)); return 100000000; } // fLendFee returns the current value of the borrowing fee used // for lending operations. // The value is returned in 4 decimals; 25 = 0.0025 = 0.25% function fLendFee() public pure returns (uint256) { return 25; } // fLendFeeDigitsCorrection represents the value to be used // to adjust result decimals after applying fee to a value calculation. function fLendFeeDigitsCorrection() public pure returns (uint256) { return 10000; } // ------------------------------------------------------------- // Lending functions below // ------------------------------------------------------------- // borrow allows user to borrow a specified token against already established // collateral. The value of the collateral must be in at least <colLowestRatio4dec> // ratio to the total user's debt value on borrowing. function borrow(address _token, uint256 _amount) external nonReentrant { // make sure the debt amount makes sense require(_amount > 0, "non-zero amount expected"); // native tokens can not be borrowed through this contract require(_token != fLendNativeToken(), "native token not borrowable"); // make sure there is some collateral established by this user // we still need to re-calculate the current value though, since the value // could have changed due to exchange rate fluctuation require(_collateralValue[msg.sender] > 0, "missing collateral"); // what is the value of the borrowed token? uint256 tokenValue = IPriceOracle(fLendPriceOracle()).getPrice(_token); require(tokenValue > 0, "token has no value"); // calculate the entry fee and remember the value we gained uint256 fee = _amount .mul(tokenValue) .mul(fLendFee()) .div(fLendFeeDigitsCorrection()) .div(fLendPriceDigitsCorrection()); feePool = feePool.add(fee); // register the debt of the fee in the fee token _debtByTokens[fLendFeeToken()][msg.sender] = _debtByTokens[fLendFeeToken()][msg.sender].add(fee); _debtByUsers[msg.sender][fLendFeeToken()] = _debtByUsers[msg.sender][fLendFeeToken()].add(fee); enrolDebt(fLendFeeToken(), msg.sender); // register the debt of borrowed token _debtByTokens[_token][msg.sender] = _debtByTokens[_token][msg.sender].add(_amount); _debtByUsers[msg.sender][_token] = _debtByUsers[msg.sender][_token].add(_amount); enrolDebt(_token, msg.sender); // recalculate current collateral and debt values in fUSD uint256 cCollateralValue = collateralValue(msg.sender); uint256 cDebtValue = debtValue(msg.sender); // minCollateralValue is the minimal collateral value required for the current debt // to be within the minimal allowed collateral to debt ratio uint256 minCollateralValue = cDebtValue .mul(collateralLowestDebtRatio4dec()) .div(collateralRatioDecimalsCorrection()); // does the new state obey the enforced minimal collateral to debt ratio? require(cCollateralValue >= minCollateralValue, "insufficient collateral"); // update the current collateral and debt value _collateralValue[msg.sender] = cCollateralValue; _debtValue[msg.sender] = cDebtValue; // transfer borrowed tokens to the user's address from the local // liquidity pool ERC20(_token).safeTransfer(msg.sender, _amount); // emit the borrow notification emit Borrow(_token, msg.sender, _amount, block.timestamp); } // repay allows user to return some of the debt of the specified token // the repay does not collect any fees and is not validating the user's total // collateral to debt position. function repay(address _token, uint256 _amount) external nonReentrant { // make sure the amount repaid makes sense require(_amount > 0, "non-zero amount expected"); // native tokens can not be borrowed through this contract // so there is no debt to be repaid on it require(_token != fLendNativeToken(), "native token not borrowable"); // subtract the returned amount from the user debt _debtByTokens[_token][msg.sender] = _debtByTokens[_token][msg.sender].sub(_amount, "insufficient debt outstanding"); _debtByUsers[msg.sender][_token] = _debtByUsers[msg.sender][_token].sub(_amount, "insufficient debt outstanding"); // update current collateral and debt amount state _collateralValue[msg.sender] = collateralValue(msg.sender); _debtValue[msg.sender] = debtValue(msg.sender); // collect the tokens to be returned back to the liquidity pool ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); // emit the repay notification emit Repay(_token, msg.sender, _amount, block.timestamp); } }
fLendFee returns the current value of the borrowing fee used for lending operations. The value is returned in 4 decimals; 25 = 0.0025 = 0.25%
function fLendFee() public pure returns (uint256) { return 25; }
5,440,556
pragma solidity ^0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "../Governance/Claimable.sol"; import "../libraries/String.sol"; import "./RenERC20.sol"; import "./interfaces/IGateway.sol"; import "../libraries/CanReclaimTokens.sol"; import "./MintGatewayV2.sol"; import "../Governance/RenProxyAdmin.sol"; contract MintGatewayUpgrader is Ownable, CanReclaimTokens { RenProxyAdmin renProxyAdmin; MintGatewayLogicV2 newGatewayLogic; address previousAdminOwner; constructor( RenProxyAdmin _renProxyAdmin, MintGatewayLogicV2 _newGatewayLogic ) public { Ownable.initialize(msg.sender); renProxyAdmin = _renProxyAdmin; newGatewayLogic = _newGatewayLogic; previousAdminOwner = renProxyAdmin.owner(); } function upgrade(MintGatewayLogicV2 gatewayInstance, bytes32 selectorHash) public onlyOwner { uint256 minimumBurnAmount = gatewayInstance.minimumBurnAmount(); RenERC20LogicV1 token = gatewayInstance.token(); address mintAuthority = gatewayInstance.mintAuthority(); address feeRecipient = gatewayInstance.feeRecipient(); uint16 mintFee = gatewayInstance.mintFee(); uint16 burnFee = gatewayInstance.burnFee(); uint256 nextN = gatewayInstance.nextN(); address previousGatewayOwner = gatewayInstance.owner(); gatewayInstance.claimOwnership(); // Update implementation. renProxyAdmin.upgrade( AdminUpgradeabilityProxy( // Cast gateway instance to payable address address(uint160(address(gatewayInstance))) ), address(newGatewayLogic) ); // Update mint authorities and selector hash. gatewayInstance.updateSelectorHash(selectorHash); require( gatewayInstance.minimumBurnAmount() == minimumBurnAmount, "Expected minimumBurnAmount to not change." ); require( gatewayInstance.token() == token, "Expected token to not change." ); require( gatewayInstance.mintAuthority() == mintAuthority, "Expected mintAuthority to equal new mintAuthority." ); require( gatewayInstance.feeRecipient() == feeRecipient, "Expected feeRecipient to not change." ); require( gatewayInstance.mintFee() == mintFee, "Expected mintFee to not change." ); require( gatewayInstance.burnFee() == burnFee, "Expected burnFee to not change." ); require( gatewayInstance.nextN() == nextN, "Expected nextN to not change." ); gatewayInstance._directTransferOwnership(previousGatewayOwner); } function done() public onlyOwner { renProxyAdmin.transferOwnership(previousAdminOwner); } } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: signature length is invalid"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: signature.s is in the wrong range"); } if (v != 27 && v != 28) { revert("ECDSA: signature.v is in the wrong range"); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } pragma solidity ^0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Initializable, Ownable { address public pendingOwner; function initialize(address _nextOwner) public initializer { Ownable.initialize(_nextOwner); } modifier onlyPendingOwner() { require( _msgSender() == pendingOwner, "Claimable: caller is not the pending owner" ); _; } function transferOwnership(address newOwner) public onlyOwner { require( newOwner != owner() && newOwner != pendingOwner, "Claimable: invalid new owner" ); pendingOwner = newOwner; } // Allow skipping two-step transfer if the recipient is known to be a valid // owner, for use in smart-contracts only. function _directTransferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } pragma solidity ^0.5.17; library String { /// @notice Convert a uint value to its decimal string representation // solium-disable-next-line security/no-assign-params function fromUint(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } /// @notice Convert a bytes32 value to its hex string representation. function fromBytes32(bytes32 _value) internal pure returns (string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(32 * 2 + 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < 32; i++) { str[2 + i * 2] = alphabet[uint256(uint8(_value[i] >> 4))]; str[3 + i * 2] = alphabet[uint256(uint8(_value[i] & 0x0f))]; } return string(str); } /// @notice Convert an address to its hex string representation. function fromAddress(address _addr) internal pure returns (string memory) { bytes32 value = bytes32(uint256(_addr)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(20 * 2 + 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < 20; i++) { str[2 + i * 2] = alphabet[uint256(uint8(value[i + 12] >> 4))]; str[3 + i * 2] = alphabet[uint256(uint8(value[i + 12] & 0x0f))]; } return string(str); } /// @notice Append eight strings. function add8( string memory a, string memory b, string memory c, string memory d, string memory e, string memory f, string memory g, string memory h ) internal pure returns (string memory) { return string(abi.encodePacked(a, b, c, d, e, f, g, h)); } } pragma solidity ^0.5.16; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; import "./ERC20WithRate.sol"; import "./ERC20WithPermit.sol"; /// @notice RenERC20 represents a digital asset that has been bridged on to /// the Ethereum ledger. It exposes mint and burn functions that can only be /// called by it's associated Gateway contract. contract RenERC20LogicV1 is Initializable, ERC20, ERC20Detailed, ERC20WithRate, ERC20WithPermit, Claimable, CanReclaimTokens { /* solium-disable-next-line no-empty-blocks */ function initialize( uint256 _chainId, address _nextOwner, uint256 _initialRate, string memory _version, string memory _name, string memory _symbol, uint8 _decimals ) public initializer { ERC20Detailed.initialize(_name, _symbol, _decimals); ERC20WithRate.initialize(_nextOwner, _initialRate); ERC20WithPermit.initialize( _chainId, _version, _name, _symbol, _decimals ); Claimable.initialize(_nextOwner); CanReclaimTokens.initialize(_nextOwner); } function updateSymbol(string memory symbol) public onlyOwner { ERC20Detailed._symbol = symbol; } /// @notice mint can only be called by the tokens' associated Gateway /// contract. See Gateway's mint function instead. function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } /// @notice burn can only be called by the tokens' associated Gateway /// contract. See Gateway's burn functions instead. function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } function transfer(address recipient, uint256 amount) public returns (bool) { // Disallow sending tokens to the ERC20 contract address - a common // mistake caused by the Ethereum transaction's `to` needing to be // the token's address. require( recipient != address(this), "RenERC20: can't transfer to token address" ); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { // Disallow sending tokens to the ERC20 contract address (see comment // in `transfer`). require( recipient != address(this), "RenERC20: can't transfer to token address" ); return super.transferFrom(sender, recipient, amount); } } /* solium-disable-next-line no-empty-blocks */ contract RenERC20Proxy is InitializableAdminUpgradeabilityProxy { } pragma solidity ^0.5.17; interface IMintGateway { function mint( bytes32 _pHash, uint256 _amount, bytes32 _nHash, bytes calldata _sig ) external returns (uint256); function mintFee() external view returns (uint256); } interface IBurnGateway { function burn(bytes calldata _to, uint256 _amountScaled) external returns (uint256); function burnFee() external view returns (uint256); } // TODO: In ^0.6.0, should be `interface IGateway is IMintGateway,IBurnGateway {}` interface IGateway { // is IMintGateway function mint( bytes32 _pHash, uint256 _amount, bytes32 _nHash, bytes calldata _sig ) external returns (uint256); function mintFee() external view returns (uint256); // is IBurnGateway function burn(bytes calldata _to, uint256 _amountScaled) external returns (uint256); function burnFee() external view returns (uint256); } pragma solidity ^0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../Governance/Claimable.sol"; contract CanReclaimTokens is Claimable { using SafeERC20 for ERC20; mapping(address => bool) private recoverableTokensBlacklist; function initialize(address _nextOwner) public initializer { Claimable.initialize(_nextOwner); } function blacklistRecoverableToken(address _token) public onlyOwner { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } } } pragma solidity ^0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "../Governance/Claimable.sol"; import "../libraries/String.sol"; import "./RenERC20.sol"; import "./interfaces/IGateway.sol"; import "../libraries/CanReclaimTokens.sol"; import "./MintGatewayV1.sol"; contract MintGatewayStateV2 { struct Burn { uint256 _blocknumber; bytes _to; uint256 _amount; // Optional string _chain; bytes _payload; } mapping(uint256 => Burn) internal burns; bytes32 public selectorHash; } /// @notice Gateway handles verifying mint and burn requests. A mintAuthority /// approves new assets to be minted by providing a digital signature. An owner /// of an asset can request for it to be burnt. contract MintGatewayLogicV2 is Initializable, Claimable, CanReclaimTokens, IGateway, MintGatewayStateV1, MintGatewayStateV2 { using SafeMath for uint256; event LogMintAuthorityUpdated(address indexed _newMintAuthority); event LogMint( address indexed _to, uint256 _amount, uint256 indexed _n, // Log the nHash instead of sHash so that it can be queried without // knowing the sHash. bytes32 indexed _nHash ); event LogBurn( bytes _to, uint256 _amount, uint256 indexed _n, bytes indexed _indexedTo ); /// @notice Only allow the Darknode Payment contract. modifier onlyOwnerOrMintAuthority() { require( msg.sender == mintAuthority || msg.sender == owner(), "MintGateway: caller is not the owner or mint authority" ); _; } /// @param _token The RenERC20 this Gateway is responsible for. /// @param _feeRecipient The recipient of burning and minting fees. /// @param _mintAuthority The address of the key that can sign mint /// requests. /// @param _mintFee The amount subtracted each mint request and /// forwarded to the feeRecipient. In BIPS. /// @param _burnFee The amount subtracted each burn request and /// forwarded to the feeRecipient. In BIPS. function initialize( RenERC20LogicV1 _token, address _feeRecipient, address _mintAuthority, uint16 _mintFee, uint16 _burnFee, uint256 _minimumBurnAmount ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); minimumBurnAmount = _minimumBurnAmount; token = _token; mintFee = _mintFee; burnFee = _burnFee; updateMintAuthority(_mintAuthority); updateFeeRecipient(_feeRecipient); } /// @param _selectorHash Hash of the token and chain selector. /// The hash should calculated from /// `SHA256(4 bytes of selector length, selector)` function updateSelectorHash(bytes32 _selectorHash) public onlyOwner { selectorHash = _selectorHash; } /// @notice Allow the owner to update the token symbol. function updateSymbol(string memory symbol) public onlyOwner { token.updateSymbol(symbol); } // Public functions //////////////////////////////////////////////////////// /// @notice Claims ownership of the token passed in to the constructor. /// `transferStoreOwnership` must have previously been called. /// Anyone can call this function. function claimTokenOwnership() public { token.claimOwnership(); } /// @notice Allow the owner to update the owner of the RenERC20 token. function transferTokenOwnership(MintGatewayLogicV2 _nextTokenOwner) public onlyOwner { token.transferOwnership(address(_nextTokenOwner)); _nextTokenOwner.claimTokenOwnership(); } /// @notice Allow the owner to update the mint authority. /// /// @param _nextMintAuthority The new mint authority address. function updateMintAuthority(address _nextMintAuthority) public onlyOwnerOrMintAuthority { // The mint authority should not be set to 0, which is the result // returned by ecrecover for an invalid signature. require( _nextMintAuthority != address(0), "MintGateway: mintAuthority cannot be set to address zero" ); mintAuthority = _nextMintAuthority; emit LogMintAuthorityUpdated(mintAuthority); } /// @notice Allow the owner to update the minimum burn amount. /// /// @param _minimumBurnAmount The new min burn amount. function updateMinimumBurnAmount(uint256 _minimumBurnAmount) public onlyOwner { minimumBurnAmount = _minimumBurnAmount; } /// @notice Allow the owner to update the fee recipient. /// /// @param _nextFeeRecipient The address to start paying fees to. function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner { // 'mint' and 'burn' will fail if the feeRecipient is 0x0 require( _nextFeeRecipient != address(0x0), "MintGateway: fee recipient cannot be 0x0" ); feeRecipient = _nextFeeRecipient; } /// @notice Allow the owner to update the 'mint' fee. /// /// @param _nextMintFee The new fee for minting and burning. function updateMintFee(uint16 _nextMintFee) public onlyOwner { mintFee = _nextMintFee; } /// @notice Allow the owner to update the burn fee. /// /// @param _nextBurnFee The new fee for minting and burning. function updateBurnFee(uint16 _nextBurnFee) public onlyOwner { burnFee = _nextBurnFee; } /// @notice Allow the owner to update the mint and burn fees. /// /// @param _nextMintFee The new fee for minting and burning. /// @param _nextBurnFee The new fee for minting and burning. function updateFees(uint16 _nextMintFee, uint16 _nextBurnFee) public onlyOwner { mintFee = _nextMintFee; burnFee = _nextBurnFee; } /// @notice mint verifies a mint approval signature from RenVM and creates /// tokens after taking a fee for the `_feeRecipient`. /// /// @param _pHash (payload hash) The hash of the payload associated with the /// mint. /// @param _amountUnderlying The amount of the token being minted, in its smallest /// value. (e.g. satoshis for BTC). /// @param _nHash (nonce hash) The hash of the nonce, amount and pHash. /// @param _sig The signature of the hash of the following values: /// (pHash, amount, msg.sender, nHash), signed by the mintAuthority. function mint( bytes32 _pHash, uint256 _amountUnderlying, bytes32 _nHash, bytes memory _sig ) public returns (uint256) { // Calculate the hash signed by RenVM. bytes32 sigHash = hashForSignature(_pHash, _amountUnderlying, msg.sender, _nHash); // Calculate the v0.2 signature hash for backwards-compatibility. bytes32 legacySigHash = _legacy_hashForSignature( _pHash, _amountUnderlying, msg.sender, _nHash ); // Check that neither signature has been redeemed. require( status[sigHash] == false && status[legacySigHash] == false, "MintGateway: nonce hash already spent" ); // If both signatures fail verification, throw an error. If any one of // them passed the verification, continue. if ( !verifySignature(sigHash, _sig) && !verifySignature(legacySigHash, _sig) ) { // Return a detailed string containing the hash and recovered // signer. This is somewhat costly but is only run in the revert // branch. revert( String.add8( "MintGateway: invalid signature. pHash: ", String.fromBytes32(_pHash), ", amount: ", String.fromUint(_amountUnderlying), ", msg.sender: ", String.fromAddress(msg.sender), ", _nHash: ", String.fromBytes32(_nHash) ) ); } // Update the status for both signature hashes. This is to ensure that // legacy signatures can't be re-redeemed if `updateSelectorHash` is // ever called - thus changing the result of `sigHash` but not // `legacySigHash`. status[sigHash] = true; status[legacySigHash] = true; uint256 amountScaled = token.fromUnderlying(_amountUnderlying); // Mint `amount - fee` for the recipient and mint `fee` for the minter uint256 absoluteFeeScaled = amountScaled.mul(mintFee).div(BIPS_DENOMINATOR); uint256 receivedAmountScaled = amountScaled.sub( absoluteFeeScaled, "MintGateway: fee exceeds amount" ); // Mint amount minus the fee token.mint(msg.sender, receivedAmountScaled); // Mint the fee if (absoluteFeeScaled > 0) { token.mint(feeRecipient, absoluteFeeScaled); } // Emit a log with a unique identifier 'n'. uint256 receivedAmountUnderlying = token.toUnderlying(receivedAmountScaled); emit LogMint(msg.sender, receivedAmountUnderlying, nextN, _nHash); nextN += 1; return receivedAmountScaled; } /// @notice burn destroys tokens after taking a fee for the `_feeRecipient`, /// allowing the associated assets to be released on their native /// chain. /// /// @param _to The address to receive the un-bridged asset. The format of /// this address should be of the destination chain. /// For example, when burning to Bitcoin, _to should be a /// Bitcoin address. /// @param _amount The amount of the token being burnt, in its /// smallest value. (e.g. satoshis for BTC) function burn(bytes memory _to, uint256 _amount) public returns (uint256) { // The recipient must not be empty. Better validation is possible, // but would need to be customized for each destination ledger. require(_to.length != 0, "MintGateway: to address is empty"); // Calculate fee, subtract it from amount being burnt. uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR); uint256 amountAfterFee = _amount.sub(fee, "MintGateway: fee exceeds amount"); // If the scaled token can represent more precision than the underlying // token, the difference is lost. This won't exceed 1 sat, so is // negligible compared to burning and transaction fees. uint256 amountAfterFeeUnderlying = token.toUnderlying(amountAfterFee); // Burn the whole amount, and then re-mint the fee. token.burn(msg.sender, _amount); if (fee > 0) { token.mint(feeRecipient, fee); } require( // Must be strictly greater, to that the release transaction is of // at least one unit. amountAfterFeeUnderlying > minimumBurnAmount, "MintGateway: amount is less than the minimum burn amount" ); emit LogBurn(_to, amountAfterFeeUnderlying, nextN, _to); // Store burn so that it can be looked up instead of relying on event // logs. bytes memory payload; MintGatewayStateV2.burns[nextN] = Burn({ _blocknumber: block.number, _to: _to, _amount: amountAfterFeeUnderlying, _chain: "", _payload: payload }); nextN += 1; return amountAfterFeeUnderlying; } function getBurn(uint256 _n) public view returns ( uint256 _blocknumber, bytes memory _to, uint256 _amount, // Optional string memory _chain, bytes memory _payload ) { Burn memory burnStruct = MintGatewayStateV2.burns[_n]; require(burnStruct._to.length > 0, "MintGateway: burn not found"); return ( burnStruct._blocknumber, burnStruct._to, burnStruct._amount, burnStruct._chain, burnStruct._payload ); } /// @notice verifySignature checks the the provided signature matches the /// provided parameters. function verifySignature(bytes32 _sigHash, bytes memory _sig) public view returns (bool) { return mintAuthority == ECDSA.recover(_sigHash, _sig); } /// @notice hashForSignature hashes the parameters so that they can be /// signed. function hashForSignature( bytes32 _pHash, uint256 _amount, address _to, bytes32 _nHash ) public view returns (bytes32) { return keccak256(abi.encode(_pHash, _amount, selectorHash, _to, _nHash)); } /// @notice _legacy_hashForSignature calculates the signature hash used by /// the 0.2 version of RenVM. It's kept here for backwards-compatibility. function _legacy_hashForSignature( bytes32 _pHash, uint256 _amount, address _to, bytes32 _nHash ) public view returns (bytes32) { return keccak256(abi.encode(_pHash, _amount, address(token), _to, _nHash)); } } /* solium-disable-next-line no-empty-blocks */ contract MintGatewayProxy is InitializableAdminUpgradeabilityProxy { } pragma solidity ^0.5.17; import "@openzeppelin/upgrades/contracts/upgradeability/ProxyAdmin.sol"; /** * @title RenProxyAdmin * @dev Proxies restrict the proxy's owner from calling functions from the * delegate contract logic. The ProxyAdmin contract allows single account to be * the governance address of both the proxy and the delegate contract logic. */ /* solium-disable-next-line no-empty-blocks */ contract RenProxyAdmin is ProxyAdmin { } pragma solidity ^0.5.0; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; import './Proxy.sol'; import '../utils/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity ^0.5.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string internal _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } pragma solidity ^0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../Governance/Claimable.sol"; /// @notice ERC20WithRate allows for a more dynamic fee model by storing a rate /// that tracks the number of the underlying asset's unit represented by a /// single ERC20 token. contract ERC20WithRate is Initializable, Ownable, ERC20 { using SafeMath for uint256; uint256 public constant _rateScale = 1e18; uint256 internal _rate; event LogRateChanged(uint256 indexed _rate); /* solium-disable-next-line no-empty-blocks */ function initialize(address _nextOwner, uint256 _initialRate) public initializer { Ownable.initialize(_nextOwner); _setRate(_initialRate); } function setExchangeRate(uint256 _nextRate) public onlyOwner { _setRate(_nextRate); } function exchangeRateCurrent() public view returns (uint256) { require(_rate != 0, "ERC20WithRate: rate has not been initialized"); return _rate; } function _setRate(uint256 _nextRate) internal { require(_nextRate > 0, "ERC20WithRate: rate must be greater than zero"); _rate = _nextRate; } function balanceOfUnderlying(address _account) public view returns (uint256) { return toUnderlying(balanceOf(_account)); } function toUnderlying(uint256 _amount) public view returns (uint256) { return _amount.mul(_rate).div(_rateScale); } function fromUnderlying(uint256 _amountUnderlying) public view returns (uint256) { return _amountUnderlying.mul(_rateScale).div(_rate); } } pragma solidity ^0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; /// @notice Taken from the DAI token. contract ERC20WithPermit is Initializable, ERC20, ERC20Detailed { using SafeMath for uint256; mapping(address => uint256) public nonces; // If the token is redeployed, the version is increased to prevent a permit // signature being used on both token instances. string public version; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // PERMIT_TYPEHASH is the value returned from // keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)") bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; function initialize( uint256 _chainId, string memory _version, string memory _name, string memory _symbol, uint8 _decimals ) public initializer { ERC20Detailed.initialize(_name, _symbol, _decimals); version = _version; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name())), keccak256(bytes(version)), _chainId, address(this) ) ); } // --- Approve by signature --- function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed ) ) ) ); require(holder != address(0), "ERC20WithRate: address must not be 0x0"); require( holder == ecrecover(digest, v, r, s), "ERC20WithRate: invalid signature" ); require( expiry == 0 || now <= expiry, "ERC20WithRate: permit has expired" ); require(nonce == nonces[holder]++, "ERC20WithRate: invalid nonce"); uint256 amount = allowed ? uint256(-1) : 0; _approve(holder, spender, amount); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "../Governance/Claimable.sol"; import "../libraries/String.sol"; import "./RenERC20.sol"; import "./interfaces/IGateway.sol"; import "../libraries/CanReclaimTokens.sol"; contract MintGatewayStateV1 { uint256 constant BIPS_DENOMINATOR = 10000; uint256 public minimumBurnAmount; /// @notice Each Gateway is tied to a specific RenERC20 token. RenERC20LogicV1 public token; /// @notice The mintAuthority is an address that can sign mint requests. address public mintAuthority; /// @dev feeRecipient is assumed to be an address (or a contract) that can /// accept erc20 payments it cannot be 0x0. /// @notice When tokens are mint or burnt, a portion of the tokens are /// forwarded to a fee recipient. address public feeRecipient; /// @notice The mint fee in bips. uint16 public mintFee; /// @notice The burn fee in bips. uint16 public burnFee; /// @notice Each signature can only be seen once. mapping(bytes32 => bool) public status; // LogMint and LogBurn contain a unique `n` that identifies // the mint or burn event. uint256 public nextN = 0; } /// @notice Gateway handles verifying mint and burn requests. A mintAuthority /// approves new assets to be minted by providing a digital signature. An owner /// of an asset can request for it to be burnt. contract MintGatewayLogicV1 is Initializable, Claimable, CanReclaimTokens, IGateway, MintGatewayStateV1 { using SafeMath for uint256; event LogMintAuthorityUpdated(address indexed _newMintAuthority); event LogMint( address indexed _to, uint256 _amount, uint256 indexed _n, bytes32 indexed _signedMessageHash ); event LogBurn( bytes _to, uint256 _amount, uint256 indexed _n, bytes indexed _indexedTo ); /// @notice Only allow the Darknode Payment contract. modifier onlyOwnerOrMintAuthority() { require( msg.sender == mintAuthority || msg.sender == owner(), "Gateway: caller is not the owner or mint authority" ); _; } /// @param _token The RenERC20 this Gateway is responsible for. /// @param _feeRecipient The recipient of burning and minting fees. /// @param _mintAuthority The address of the key that can sign mint /// requests. /// @param _mintFee The amount subtracted each mint request and /// forwarded to the feeRecipient. In BIPS. /// @param _burnFee The amount subtracted each burn request and /// forwarded to the feeRecipient. In BIPS. function initialize( RenERC20LogicV1 _token, address _feeRecipient, address _mintAuthority, uint16 _mintFee, uint16 _burnFee, uint256 _minimumBurnAmount ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); minimumBurnAmount = _minimumBurnAmount; token = _token; mintFee = _mintFee; burnFee = _burnFee; updateMintAuthority(_mintAuthority); updateFeeRecipient(_feeRecipient); } // Public functions //////////////////////////////////////////////////////// /// @notice Claims ownership of the token passed in to the constructor. /// `transferStoreOwnership` must have previously been called. /// Anyone can call this function. function claimTokenOwnership() public { token.claimOwnership(); } /// @notice Allow the owner to update the owner of the RenERC20 token. function transferTokenOwnership(MintGatewayLogicV1 _nextTokenOwner) public onlyOwner { token.transferOwnership(address(_nextTokenOwner)); _nextTokenOwner.claimTokenOwnership(); } /// @notice Allow the owner to update the mint authority. /// /// @param _nextMintAuthority The new mint authority address. function updateMintAuthority(address _nextMintAuthority) public onlyOwnerOrMintAuthority { // The mint authority should not be set to 0, which is the result // returned by ecrecover for an invalid signature. require( _nextMintAuthority != address(0), "Gateway: mintAuthority cannot be set to address zero" ); mintAuthority = _nextMintAuthority; emit LogMintAuthorityUpdated(mintAuthority); } /// @notice Allow the owner to update the minimum burn amount. /// /// @param _minimumBurnAmount The new min burn amount. function updateMinimumBurnAmount(uint256 _minimumBurnAmount) public onlyOwner { minimumBurnAmount = _minimumBurnAmount; } /// @notice Allow the owner to update the fee recipient. /// /// @param _nextFeeRecipient The address to start paying fees to. function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner { // 'mint' and 'burn' will fail if the feeRecipient is 0x0 require( _nextFeeRecipient != address(0x0), "Gateway: fee recipient cannot be 0x0" ); feeRecipient = _nextFeeRecipient; } /// @notice Allow the owner to update the 'mint' fee. /// /// @param _nextMintFee The new fee for minting and burning. function updateMintFee(uint16 _nextMintFee) public onlyOwner { mintFee = _nextMintFee; } /// @notice Allow the owner to update the burn fee. /// /// @param _nextBurnFee The new fee for minting and burning. function updateBurnFee(uint16 _nextBurnFee) public onlyOwner { burnFee = _nextBurnFee; } /// @notice mint verifies a mint approval signature from RenVM and creates /// tokens after taking a fee for the `_feeRecipient`. /// /// @param _pHash (payload hash) The hash of the payload associated with the /// mint. /// @param _amountUnderlying The amount of the token being minted, in its smallest /// value. (e.g. satoshis for BTC). /// @param _nHash (nonce hash) The hash of the nonce, amount and pHash. /// @param _sig The signature of the hash of the following values: /// (pHash, amount, msg.sender, nHash), signed by the mintAuthority. function mint( bytes32 _pHash, uint256 _amountUnderlying, bytes32 _nHash, bytes memory _sig ) public returns (uint256) { // Calculate the hash signed by RenVM. bytes32 sigHash = hashForSignature(_pHash, _amountUnderlying, msg.sender, _nHash); // // Check that the signature hasn't been redeemed. require(status[sigHash] == false, "Gateway: nonce hash already spent"); // If the signature fails verification, throw an error. If any one of // them passed the verification, continue. if (!verifySignature(sigHash, _sig)) { // Return a detailed string containing the hash and recovered // signer. This is somewhat costly but is only run in the revert // branch. revert( String.add8( "Gateway: invalid signature. pHash: ", String.fromBytes32(_pHash), ", amount: ", String.fromUint(_amountUnderlying), ", msg.sender: ", String.fromAddress(msg.sender), ", _nHash: ", String.fromBytes32(_nHash) ) ); } // Update the status for the signature hash so that it can't be used // again. status[sigHash] = true; uint256 amountScaled = token.fromUnderlying(_amountUnderlying); // Mint `amount - fee` for the recipient and mint `fee` for the minter uint256 absoluteFeeScaled = amountScaled.mul(mintFee).div(BIPS_DENOMINATOR); uint256 receivedAmountScaled = amountScaled.sub(absoluteFeeScaled, "Gateway: fee exceeds amount"); // Mint amount minus the fee token.mint(msg.sender, receivedAmountScaled); // Mint the fee token.mint(feeRecipient, absoluteFeeScaled); // Emit a log with a unique identifier 'n'. uint256 receivedAmountUnderlying = token.toUnderlying(receivedAmountScaled); emit LogMint(msg.sender, receivedAmountUnderlying, nextN, sigHash); nextN += 1; return receivedAmountScaled; } /// @notice burn destroys tokens after taking a fee for the `_feeRecipient`, /// allowing the associated assets to be released on their native /// chain. /// /// @param _to The address to receive the un-bridged asset. The format of /// this address should be of the destination chain. /// For example, when burning to Bitcoin, _to should be a /// Bitcoin address. /// @param _amount The amount of the token being burnt, in its /// smallest value. (e.g. satoshis for BTC) function burn(bytes memory _to, uint256 _amount) public returns (uint256) { // The recipient must not be empty. Better validation is possible, // but would need to be customized for each destination ledger. require(_to.length != 0, "Gateway: to address is empty"); // Calculate fee, subtract it from amount being burnt. uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR); uint256 amountAfterFee = _amount.sub(fee, "Gateway: fee exceeds amount"); // If the scaled token can represent more precision than the underlying // token, the difference is lost. This won't exceed 1 sat, so is // negligible compared to burning and transaction fees. uint256 amountAfterFeeUnderlying = token.toUnderlying(amountAfterFee); // Burn the whole amount, and then re-mint the fee. token.burn(msg.sender, _amount); token.mint(feeRecipient, fee); require( // Must be strictly greater, to that the release transaction is of // at least one unit. amountAfterFeeUnderlying > minimumBurnAmount, "Gateway: amount is less than the minimum burn amount" ); emit LogBurn(_to, amountAfterFeeUnderlying, nextN, _to); nextN += 1; return amountAfterFeeUnderlying; } /// @notice verifySignature checks the the provided signature matches the /// provided parameters. function verifySignature(bytes32 _sigHash, bytes memory _sig) public view returns (bool) { return mintAuthority == ECDSA.recover(_sigHash, _sig); } /// @notice hashForSignature hashes the parameters so that they can be /// signed. function hashForSignature( bytes32 _pHash, uint256 _amount, address _to, bytes32 _nHash ) public view returns (bytes32) { return keccak256(abi.encode(_pHash, _amount, address(token), _to, _nHash)); } } contract BTCGateway is InitializableAdminUpgradeabilityProxy {} contract ZECGateway is InitializableAdminUpgradeabilityProxy {} contract BCHGateway is InitializableAdminUpgradeabilityProxy {} pragma solidity ^0.5.0; import "../ownership/Ownable.sol"; import "./AdminUpgradeabilityProxy.sol"; /** * @title ProxyAdmin * @dev This contract is the admin of a proxy, and is in charge * of upgrading it as well as transferring it to another admin. */ contract ProxyAdmin is OpenZeppelinUpgradesOwnable { /** * @dev Returns the current implementation of a proxy. * This is needed because only the proxy admin can query it. * @return The address of the current implementation of the proxy. */ function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the admin of a proxy. Only the admin can query it. * @return The address of the current admin of the proxy. */ function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of a proxy. * @param proxy Proxy to change admin. * @param newAdmin Address to transfer proxy administration to. */ function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades a proxy to the newest implementation of a contract. * @param proxy Proxy to be upgraded. * @param implementation the address of the Implementation. */ function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades a proxy to the newest implementation of a contract and forwards a function call to it. * This is useful to initialize the proxied contract. * @param proxy Proxy to be upgraded. * @param implementation Address of the Implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes memory data) payable public onlyOwner { proxy.upgradeToAndCall.value(msg.value)(implementation, data); } } pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version. */ contract OpenZeppelinUpgradesOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } }
TODO: In ^0.6.0, should be `interface IGateway is IMintGateway,IBurnGateway {}` is IMintGateway is IBurnGateway
interface IGateway { function mint( bytes32 _pHash, uint256 _amount, bytes32 _nHash, bytes calldata _sig ) external returns (uint256); function mintFee() external view returns (uint256); function burn(bytes calldata _to, uint256 _amountScaled) external returns (uint256); function burnFee() external view returns (uint256); }
13,617,443
pragma solidity ^0.4.22; import "./openzeppelin/contracts/math/SafeMath.sol"; import "./openzeppelin/contracts/lifecycle/Pausable.sol"; import "./EtherDollar.sol"; import "./Liquidator.sol"; /** * @title EtherBank contract. */ contract EtherBank is Pausable { using SafeMath for uint256; address public owner; address public oracleAddr; address public liquidatorAddr; address public etherDollarAddr; uint256 public lastLoanId; uint256 public etherPrice; // cent uint256 public depositRate; uint256 public liquidationDuration; // duration of liquidation in Seconds EtherDollar internal token; Liquidator internal liquidator; uint256 constant internal PRECISION_POINT = 10 ** 3; uint256 constant internal ETHER_TO_WEI = 10 ** 18; enum Types { ETHER_PRICE, DEPOSIT_RATE, LIQUIDATION_DURATION } enum LoanState { ACTIVE, UNDER_LIQUIDATION, LIQUIDATED, SETTLED } struct Loan { address debtor; uint256 collateralAmount; uint256 amount; LoanState state; } mapping(uint256 => Loan) private loans; event LoanGot(address indexed borrower, uint256 indexed loanId, uint256 collateralAmount, uint256 amount); event IncreaseCollatral(address indexed borrower, uint256 indexed loanId, uint256 collateralAmount); event LoanSettled(address borrower, uint256 indexed loanId, uint256 collateralAmount, uint256 amount); string private constant INVALID_ADDRESS = "INVALID_ADDRESS"; string private constant ONLY_ORACLES = "ONLY_ORACLE"; string private constant INVALID_AMOUNT = "INVALID_AMOUNT"; string private constant COLLATERAL_NOT_ENOUGH = "COLLATERAL_NOT_ENOUGH"; string private constant ONLY_LOAN_OWNER = "ONLY_LOAN_OWNER"; string private constant NOT_ENOUGH_ALLOWANCE = "NOT_ENOUGH_ALLOWANCE"; string private constant NOT_ACTIVE_LOAN = "NOT_ACTIVE_LOAN"; string private constant ENOUGH_COLLATERAL = "ENOUGH_COLLATERAL"; string private constant ONLY_LIQUIDATOR = "ONLY_LIQUIDATOR"; constructor(address _tokenAdd) public { token = EtherDollar(_tokenAdd); etherDollarAddr = _tokenAdd; owner = msg.sender; etherPrice = 0; // IN Cent depositRate = 1500; // = 1.5 lastLoanId = 0; liquidationDuration = 7200; // IN Seconds } /** * @dev Fallback function. */ function() external payable { uint256 amount = msg.value.mul(PRECISION_POINT * etherPrice).div(2 * depositRate * ETHER_TO_WEI); getLoan(amount); } /** * @notice Set Liquidator smart contract. * @param _liquidatorAddr The Liquidator smart contract address. */ function setLiquidator(address _liquidatorAddr) external onlyOwner { require(_liquidatorAddr != address(0), INVALID_ADDRESS); liquidatorAddr = _liquidatorAddr; liquidator = Liquidator(liquidatorAddr); } /** * @notice Set EtherDollar smart contract address. * @param _tokenAdd The EtherDollar smart contract address. */ function setEtherDollar(address _tokenAdd) external onlyOwner { require(_tokenAdd != address(0), INVALID_ADDRESS); token = EtherDollar(_tokenAdd); } /** * @notice Set oracle address. * @param _oracleAddr The oracle's address. */ function setOracle(address _oracleAddr) external onlyOwner { require(_oracleAddr != address(0), INVALID_ADDRESS); oracleAddr = _oracleAddr; } /** * @notice Lets Oracle to set important varibales. * @param _type Code of the variable. * @param value Amount of the variable. */ function setVariable(uint256 _type, uint256 value) external onlyOracles { if (uint(Types.ETHER_PRICE) == _type) { etherPrice = value; } else if (uint(Types.DEPOSIT_RATE) == _type) { depositRate = value; } else if (uint(Types.LIQUIDATION_DURATION) == _type) { liquidationDuration = value; } } /** * @notice deposit ethereum to borrow etherDollar. * @param amount The amount of requsted loan. */ function getLoan(uint256 amount) public payable whenNotPaused throwIfEqualToZero(amount) enoughCollateral(amount) { uint256 loanId = ++lastLoanId; loans[loanId].debtor = msg.sender; loans[loanId].collateralAmount = msg.value; loans[loanId].amount = amount; loans[loanId].state = LoanState.ACTIVE; emit LoanGot(msg.sender, loanId, msg.value, amount); token.mint(msg.sender, amount); } /** * @notice increase the loan's collatral. * @param loanId The loan id. */ function increaseCollatral(uint256 loanId) external payable whenNotPaused onlyLoanOwner(loanId) { require(msg.value > 0, COLLATERAL_NOT_ENOUGH); require(loans[loanId].state == LoanState.ACTIVE, NOT_ACTIVE_LOAN); loans[loanId].collateralAmount.add(msg.value); emit IncreaseCollatral(msg.sender, loanId, msg.value); } /** * @notice payback etherDollars. * @param amount The etherDollar amount payed back. * @param loanId The loan id. */ function settleLoan(uint256 amount, uint256 loanId) external whenNotPaused onlyLoanOwner(loanId) throwIfEqualToZero(amount) { require(amount <= token.allowance(msg.sender, this), NOT_ENOUGH_ALLOWANCE); require(amount <= loans[loanId].amount, INVALID_AMOUNT); require(loans[loanId].state == LoanState.ACTIVE, NOT_ACTIVE_LOAN); uint256 paybackCollateralAmount = loans[loanId].collateralAmount.mul(amount).div(loans[loanId].amount); if (token.transferFrom(msg.sender, this, amount)) { token.burn(amount); loans[loanId].collateralAmount -= paybackCollateralAmount; loans[loanId].amount -= amount; if (loans[loanId].amount == 0) { loans[loanId].state = LoanState.SETTLED; } emit LoanSettled(msg.sender, loanId, paybackCollateralAmount, amount); msg.sender.transfer(paybackCollateralAmount); } } /** * @notice liquidate collateral of the loan. * @param loanId The loan id. */ function liquidate(uint256 loanId) external whenNotPaused { require((loans[loanId].collateralAmount * etherPrice * PRECISION_POINT) < (loans[loanId].amount * depositRate * ETHER_TO_WEI), ENOUGH_COLLATERAL); require(loans[loanId].state == LoanState.ACTIVE, NOT_ACTIVE_LOAN); loans[loanId].state = LoanState.UNDER_LIQUIDATION; liquidator.startLiquidation( loanId, loans[loanId].collateralAmount, loans[loanId].amount ); } /** * @dev pay winner of auction's ether. * @param loanId The loan id. * @param amount The bid of winner. * @param buyer The winner account. */ function liquidated(uint256 loanId, uint256 amount, address buyer) external whenNotPaused onlyLiquidator { loans[loanId].state = LoanState.LIQUIDATED; loans[loanId].collateralAmount -= amount; loans[loanId].amount = 0; buyer.transfer(amount); } /** * @dev Throws if called by any account other than our Oracle. */ modifier onlyOracles() { require(msg.sender == oracleAddr, ONLY_ORACLES); _; } /** * @dev Throws if called by any account other than our Liquidator. */ modifier onlyLiquidator() { require(msg.sender == liquidatorAddr, ONLY_LIQUIDATOR); _; } /** * @dev Throws if the number is equal to zero. * @param number The number to validate. */ modifier throwIfEqualToZero(uint number) { require(number != 0, INVALID_AMOUNT); _; } /** * @dev Throws if the collateral is not enough for requested loan. * @param loanAmount The amount of requsted loan. */ modifier enoughCollateral(uint256 loanAmount) { require((msg.value * etherPrice * PRECISION_POINT) >= (loanAmount * depositRate * ETHER_TO_WEI), COLLATERAL_NOT_ENOUGH); _; } /** * @dev Throws if called by any account other than the owner of the loan. * @param loanId The loan id. */ modifier onlyLoanOwner(uint256 loanId) { require(loans[loanId].debtor == msg.sender, ONLY_LOAN_OWNER); _; } }
payback etherDollars. amount The etherDollar amount payed back. loanId The loan id./
function settleLoan(uint256 amount, uint256 loanId) external whenNotPaused onlyLoanOwner(loanId) throwIfEqualToZero(amount) { require(amount <= token.allowance(msg.sender, this), NOT_ENOUGH_ALLOWANCE); require(amount <= loans[loanId].amount, INVALID_AMOUNT); require(loans[loanId].state == LoanState.ACTIVE, NOT_ACTIVE_LOAN); uint256 paybackCollateralAmount = loans[loanId].collateralAmount.mul(amount).div(loans[loanId].amount); if (token.transferFrom(msg.sender, this, amount)) { token.burn(amount); loans[loanId].collateralAmount -= paybackCollateralAmount; loans[loanId].amount -= amount; if (loans[loanId].amount == 0) { loans[loanId].state = LoanState.SETTLED; } emit LoanSettled(msg.sender, loanId, paybackCollateralAmount, amount); msg.sender.transfer(paybackCollateralAmount); } }
12,733,055
./full_match/4/0x68bb830874D36ea13d14daB9dD774E7c350D9c94/sources/contracts/ZeroInterestMarket.sol
recover tokens inadvertantly sent to this contract by transfering them to the owner _token the address of the token _amount the amount to transfer/
function recoverERC20(address _token, uint256 _amount) external onlyOwner { require(_token != address(debtToken), "Cannot recover debt tokens"); require(_token != address(collateralToken), "Cannot recover collateral tokens"); IERC20(_token).safeTransfer(msg.sender, _amount); }
695,216
./partial_match/1313161554/0x5749c1374cc9DE28B94cf054dEb303D4cA3464bF/sources/contracts/distribution/PolarRewardPool.sol
Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accPolarPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safePolarTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accPolarPerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); }
16,913,318
/** *Submitted for verification at Etherscan.io on 2019-10-31 */ /************************************************************************** * ____ _ * / ___| | | __ _ _ _ ___ _ __ * | | _____ | | / _` || | | | / _ \| '__| * | |___|_____|| |___| (_| || |_| || __/| | * \____| |_____|\__,_| \__, | \___||_| * |___/ * ************************************************************************** * * The MIT License (MIT) * * Copyright (c) 2016-2019 Cyril Lapinte * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************** * * Flatten Contract: Tokensale * * Git Commit: * https://github.com/c-layer/contracts/tree/43925ba24cc22f42d0ff7711d0e169e8c2a0e09f * **************************************************************************/ // File: contracts/interface/IERC20.sol pragma solidity >=0.5.0 <0.6.0; /** * @title IERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract IERC20 { function name() public view returns (string memory); function symbol() public view returns (string memory); function decimals() public view returns (uint256); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function increaseApproval(address spender, uint addedValue) public returns (bool); function decreaseApproval(address spender, uint subtractedValue) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/interface/ITokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title ITokensale * @dev ITokensale interface * * @author Cyril Lapinte - <[email protected]> */ contract ITokensale { function () external payable; function investETH() public payable; function token() public view returns (IERC20); function vaultETH() public view returns (address); function vaultERC20() public view returns (address); function tokenPrice() public view returns (uint256); function totalRaised() public view returns (uint256); function totalUnspentETH() public view returns (uint256); function totalRefundedETH() public view returns (uint256); function availableSupply() public view returns (uint256); function investorUnspentETH(address _investor) public view returns (uint256); function investorInvested(address _investor) public view returns (uint256); function investorTokens(address _investor) public view returns (uint256); function tokenInvestment(address _investor, uint256 _amount) public view returns (uint256); function refundManyUnspentETH(address payable[] memory _receivers) public returns (bool); function refundUnspentETH() public returns (bool); function withdrawAllETHFunds() public returns (bool); function fundETH() public payable; event RefundETH(address indexed recipient, uint256 amount); event WithdrawETH(uint256 amount); event FundETH(uint256 amount); event Investment(address indexed investor, uint256 invested, uint256 tokens); } // File: contracts/util/math/SafeMath.sol pragma solidity >=0.5.0 <0.6.0; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/util/governance/Ownable.sol pragma solidity >=0.5.0 <0.6.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/util/governance/Operable.sol pragma solidity >=0.5.0 <0.6.0; /** * @title Operable * @dev The Operable contract enable the restrictions of operations to a set of operators * * @author Cyril Lapinte - <[email protected]> * * Error messages * OP01: Message sender must be an operator * OP02: Address must be an operator * OP03: Address must not be an operator */ contract Operable is Ownable { mapping (address => bool) private operators_; /** * @dev Throws if called by any account other than the operator */ modifier onlyOperator { require(operators_[msg.sender], "OP01"); _; } /** * @dev constructor */ constructor() public { defineOperator("Owner", msg.sender); } /** * @dev isOperator * @param _address operator address */ function isOperator(address _address) public view returns (bool) { return operators_[_address]; } /** * @dev removeOperator * @param _address operator address */ function removeOperator(address _address) public onlyOwner { require(operators_[_address], "OP02"); operators_[_address] = false; emit OperatorRemoved(_address); } /** * @dev defineOperator * @param _role operator role * @param _address operator address */ function defineOperator(string memory _role, address _address) public onlyOwner { require(!operators_[_address], "OP03"); operators_[_address] = true; emit OperatorDefined(_role, _address); } event OperatorRemoved(address address_); event OperatorDefined( string role, address address_ ); } // File: contracts/util/lifecycle/Pausable.sol pragma solidity >=0.5.0 <0.6.0; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * * Error messages * PA01: the contract is paused * PA02: the contract is unpaused **/ contract Pausable is Operable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "PA01"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "PA02"); _; } /** * @dev called by the operator to pause, triggers stopped state */ function pause() public onlyOperator whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the operator to unpause, returns to normal state */ function unpause() public onlyOperator whenPaused { paused = false; emit Unpause(); } } // File: contracts/tokensale/BaseTokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title BaseTokensale * @dev Base Tokensale contract * * @author Cyril Lapinte - <[email protected]> * * Error messages * TOS01: token price must be strictly positive * TOS02: price unit must be strictly positive * TOS03: No data must be sent while sending ETH * TOS04: Token transfer must be successfull * TOS05: No ETH to refund * TOS06: Cannot invest 0 tokens * TOS07: Cannot invest if there are no tokens to buy * TOS08: Only exact amount is authorized */ contract BaseTokensale is ITokensale, Operable, Pausable { using SafeMath for uint256; /* General sale details */ IERC20 internal token_; address payable internal vaultETH_; address internal vaultERC20_; uint256 internal tokenPrice_; uint256 internal priceUnit_; uint256 internal totalRaised_; uint256 internal totalTokensSold_; uint256 internal totalUnspentETH_; uint256 internal totalRefundedETH_; struct Investor { uint256 unspentETH; uint256 invested; uint256 tokens; } mapping(address => Investor) internal investors; /** * @dev constructor */ constructor( IERC20 _token, address _vaultERC20, address payable _vaultETH, uint256 _tokenPrice, uint256 _priceUnit ) public { require(_tokenPrice > 0, "TOS01"); require(_priceUnit > 0, "TOS02"); token_ = _token; vaultERC20_ = _vaultERC20; vaultETH_ = _vaultETH; tokenPrice_ = _tokenPrice; priceUnit_ = _priceUnit; } /** * @dev fallback function */ //solhint-disable-next-line no-complex-fallback function () external payable { require(msg.data.length == 0, "TOS03"); investETH(); } /* Investment */ function investETH() public payable { Investor storage investor = investorInternal(msg.sender); uint256 amountETH = investor.unspentETH.add(msg.value); investInternal(msg.sender, amountETH, false); } /** * @dev returns the token sold */ function token() public view returns (IERC20) { return token_; } /** * @dev returns the vault use to */ function vaultETH() public view returns (address) { return vaultETH_; } /** * @dev returns the vault to receive ETH */ function vaultERC20() public view returns (address) { return vaultERC20_; } /** * @dev returns token price */ function tokenPrice() public view returns (uint256) { return tokenPrice_; } /** * @dev returns price unit */ function priceUnit() public view returns (uint256) { return priceUnit_; } /** * @dev returns total raised */ function totalRaised() public view returns (uint256) { return totalRaised_; } /** * @dev returns total tokens sold */ function totalTokensSold() public view returns (uint256) { return totalTokensSold_; } /** * @dev returns total unspent ETH */ function totalUnspentETH() public view returns (uint256) { return totalUnspentETH_; } /** * @dev returns total refunded ETH */ function totalRefundedETH() public view returns (uint256) { return totalRefundedETH_; } /** * @dev returns the available supply */ function availableSupply() public view returns (uint256) { uint256 vaultSupply = token_.balanceOf(vaultERC20_); uint256 allowance = token_.allowance(vaultERC20_, address(this)); return (vaultSupply < allowance) ? vaultSupply : allowance; } /* Investor specific attributes */ function investorUnspentETH(address _investor) public view returns (uint256) { return investorInternal(_investor).unspentETH; } function investorInvested(address _investor) public view returns (uint256) { return investorInternal(_investor).invested; } function investorTokens(address _investor) public view returns (uint256) { return investorInternal(_investor).tokens; } /** * @dev tokenInvestment */ function tokenInvestment(address, uint256 _amount) public view returns (uint256) { uint256 availableSupplyValue = availableSupply(); uint256 contribution = _amount.mul(priceUnit_).div(tokenPrice_); return (contribution < availableSupplyValue) ? contribution : availableSupplyValue; } /** * @dev refund unspentETH ETH many */ function refundManyUnspentETH(address payable[] memory _receivers) public onlyOperator returns (bool) { for (uint256 i = 0; i < _receivers.length; i++) { refundUnspentETHInternal(_receivers[i]); } return true; } /** * @dev refund unspentETH */ function refundUnspentETH() public returns (bool) { refundUnspentETHInternal(msg.sender); return true; } /** * @dev withdraw all ETH funds */ function withdrawAllETHFunds() public onlyOperator returns (bool) { uint256 balance = address(this).balance; withdrawETHInternal(balance); return true; } /** * @dev fund ETH */ function fundETH() public payable onlyOperator { emit FundETH(msg.value); } /** * @dev investor internal */ function investorInternal(address _investor) internal view returns (Investor storage) { return investors[_investor]; } /** * @dev eval unspent ETH internal */ function evalUnspentETHInternal( Investor storage _investor, uint256 _investedETH ) internal view returns (uint256) { return _investor.unspentETH.add(msg.value).sub(_investedETH); } /** * @dev eval investment internal */ function evalInvestmentInternal(uint256 _tokens) internal view returns (uint256, uint256) { uint256 invested = _tokens.mul(tokenPrice_).div(priceUnit_); return (invested, _tokens); } /** * @dev distribute tokens internal */ function distributeTokensInternal(address _investor, uint256 _tokens) internal { require( token_.transferFrom(vaultERC20_, _investor, _tokens), "TOS04"); } /** * @dev refund unspentETH internal */ function refundUnspentETHInternal(address payable _investor) internal { Investor storage investor = investorInternal(_investor); require(investor.unspentETH > 0, "TOS05"); uint256 unspentETH = investor.unspentETH; totalRefundedETH_ = totalRefundedETH_.add(unspentETH); totalUnspentETH_ = totalUnspentETH_.sub(unspentETH); investor.unspentETH = 0; // Multiple sends are required for refundManyUnspentETH // solhint-disable-next-line multiple-sends _investor.transfer(unspentETH); emit RefundETH(_investor, unspentETH); } /** * @dev withdraw ETH internal */ function withdrawETHInternal(uint256 _amount) internal { // Send is used after the ERC20 transfer // solhint-disable-next-line multiple-sends vaultETH_.transfer(_amount); emit WithdrawETH(_amount); } /** * @dev invest internal */ function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly) internal whenNotPaused { require(_amount != 0, "TOS06"); Investor storage investor = investorInternal(_investor); uint256 investment = tokenInvestment(_investor, _amount); require(investment != 0, "TOS07"); (uint256 invested, uint256 tokens) = evalInvestmentInternal(investment); if (_exactAmountOnly) { require(invested == _amount, "TOS08"); } else { uint256 unspentETH = evalUnspentETHInternal(investor, invested); totalUnspentETH_ = totalUnspentETH_.sub(investor.unspentETH).add(unspentETH); investor.unspentETH = unspentETH; } investor.invested = investor.invested.add(invested); investor.tokens = investor.tokens.add(tokens); totalRaised_ = totalRaised_.add(invested); totalTokensSold_ = totalTokensSold_.add(tokens); emit Investment(_investor, invested, tokens); /* Reentrancy risks: No state change must come below */ distributeTokensInternal(_investor, tokens); uint256 balance = address(this).balance; uint256 withdrawableETH = balance.sub(totalUnspentETH_); if (withdrawableETH != 0) { withdrawETHInternal(withdrawableETH); } } } // File: contracts/tokensale/SchedulableTokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title SchedulableTokensale * @dev SchedulableTokensale contract * * @author Cyril Lapinte - <[email protected]> * * Error messages * STS01: It must be before the sale is opened * STS02: Sale must be open * STS03: It must be before the sale is closed * STS04: It must be after the sale is closed * STS05: It must start before it ends. */ contract SchedulableTokensale is BaseTokensale { uint256 internal startAt = ~uint256(0); uint256 internal endAt = ~uint256(0); bool internal closed; event Schedule(uint256 startAt, uint256 endAt); event CloseEarly(); /** * @dev Throws if sale is not open */ modifier beforeSaleIsOpened { require(currentTime() < startAt && !closed, "STS01"); _; } /** * @dev Throws if sale is not open */ modifier saleIsOpened { require( currentTime() >= startAt && currentTime() <= endAt && !closed, "STS02" ); _; } /** * @dev Throws once the sale is closed */ modifier beforeSaleIsClosed { require(currentTime() <= endAt && !closed, "STS03"); _; } /** * @dev Throws once the sale is closed */ modifier afterSaleIsClosed { require(isClosed(), "STS04"); _; } /** * @dev constructor */ constructor( IERC20 _token, address _vaultERC20, address payable _vaultETH, uint256 _tokenPrice, uint256 _priceUnit ) public BaseTokensale(_token, _vaultERC20, _vaultETH, _tokenPrice, _priceUnit) {} /* solhint-disable no-empty-blocks */ /** * @dev schedule */ function schedule() public view returns (uint256, uint256) { return (startAt, endAt); } /** * @dev isClosed */ function isClosed() public view returns (bool) { return currentTime() > endAt || closed; } /** * @dev update schedule */ function updateSchedule(uint256 _startAt, uint256 _endAt) public onlyOperator beforeSaleIsOpened { require(_startAt < _endAt, "STS05"); startAt = _startAt; endAt = _endAt; emit Schedule(_startAt, _endAt); } /** * @dev close sale */ function closeEarly() public onlyOperator beforeSaleIsClosed { closed = true; emit CloseEarly(); } /* Investment */ function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly) internal saleIsOpened { super.investInternal(_investor, _amount, _exactAmountOnly); } /* Util */ /** * @dev current time */ function currentTime() internal view returns (uint256) { // solhint-disable-next-line not-rely-on-time return now; } } // File: contracts/tokensale/BonusTokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title BonusTokensale * @dev BonusTokensale contract * * @author Cyril Lapinte - <[email protected]> * * Error messages * BT01: There must have the same number of bonuses and bonusUntils * BT02: There must be some bonuses * BT03: There cannot be too many bonuses * BT04: BonusUntils must be declared in a progressive order * BT05: There cannot be bonuses with a NONE bonus mode **/ contract BonusTokensale is SchedulableTokensale { enum BonusMode { NONE, EARLY, FIRST } uint256 constant MAX_BONUSES = 10; BonusMode internal bonusMode_ = BonusMode.NONE; uint256[] internal bonusUntils_; uint256[] internal bonuses_; event BonusesDefined(uint256[] bonuses, BonusMode bonusMode, uint256[] bonusUntils); /** * @dev constructor */ constructor( IERC20 _token, address _vaultERC20, address payable _vaultETH, uint256 _tokenPrice, uint256 _priceUnit ) public SchedulableTokensale(_token, _vaultERC20, _vaultETH, _tokenPrice, _priceUnit) {} /* solhint-disable no-empty-blocks */ /** * @dev bonuses */ function bonuses() public view returns (BonusMode, uint256[] memory, uint256[] memory) { return (bonusMode_, bonuses_, bonusUntils_); } /** * @dev early bonus */ function earlyBonus(uint256 _currentTime) public view returns (uint256 bonus, uint256 remainingAtBonus) { if (bonusMode_ != BonusMode.EARLY || _currentTime < startAt || _currentTime > endAt) { return (uint256(0), uint256(-1)); } for(uint256 i=0; i < bonusUntils_.length; i++) { if (_currentTime <= bonusUntils_[i]) { return (bonuses_[i], uint256(-1)); } } return (uint256(0), uint256(-1)); } /** * @dev first bonus */ function firstBonus(uint256 _tokensSold) public view returns (uint256 bonus, uint256 remainingAtBonus) { if (bonusMode_ != BonusMode.FIRST) { return (uint256(0), uint256(-1)); } for(uint256 i=0; i < bonusUntils_.length; i++) { if (_tokensSold < bonusUntils_[i]) { return (bonuses_[i], bonusUntils_[i]-_tokensSold); } } return (uint256(0), uint256(-1)); } /** * @dev define bonus */ function defineBonuses( BonusMode _bonusMode, uint256[] memory _bonuses, uint256[] memory _bonusUntils) public onlyOperator beforeSaleIsOpened returns (bool) { require(_bonuses.length == _bonusUntils.length, "BT01"); if (_bonusMode != BonusMode.NONE) { require(_bonusUntils.length > 0, "BT02"); require(_bonusUntils.length < MAX_BONUSES, "BT03"); uint256 bonusUntil = (_bonusMode == BonusMode.EARLY) ? startAt : 0; for(uint256 i=0; i < _bonusUntils.length; i++) { require(_bonusUntils[i] > bonusUntil, "BT04"); bonusUntil = _bonusUntils[i]; } } else { require(_bonusUntils.length == 0, "BT05"); } bonuses_ = _bonuses; bonusMode_ = _bonusMode; bonusUntils_ = _bonusUntils; emit BonusesDefined(_bonuses, _bonusMode, _bonusUntils); return true; } /** * @dev current bonus */ function tokenBonus(uint256 _tokens) public view returns (uint256 tokenBonus_) { uint256 bonus; uint256 remainingAtBonus; uint256 unprocessed = _tokens; do { if(bonusMode_ == BonusMode.EARLY) { (bonus, remainingAtBonus) = earlyBonus(currentTime()); } if(bonusMode_ == BonusMode.FIRST) { (bonus, remainingAtBonus) = firstBonus(totalTokensSold_+_tokens-unprocessed); } uint256 tokensAtCurrentBonus = (unprocessed < remainingAtBonus) ? unprocessed : remainingAtBonus; tokenBonus_ += bonus.mul(tokensAtCurrentBonus).div(100); unprocessed -= tokensAtCurrentBonus; } while(bonus > 0 && unprocessed > 0 && remainingAtBonus > 0); } /** * @dev eval investment internal */ function evalInvestmentInternal(uint256 _tokens) internal view returns (uint256, uint256) { (uint256 invested, uint256 tokens) = super.evalInvestmentInternal(_tokens); uint256 bonus = tokenBonus(tokens); return (invested, tokens.add(bonus)); } } // File: contracts/interface/IRatesProvider.sol pragma solidity >=0.5.0 <0.6.0; /** * @title IRatesProvider * @dev IRatesProvider interface * * @author Cyril Lapinte - <[email protected]> */ contract IRatesProvider { function defineRatesExternal(uint256[] calldata _rates) external returns (bool); function name() public view returns (string memory); function rate(bytes32 _currency) public view returns (uint256); function currencies() public view returns (bytes32[] memory, uint256[] memory, uint256); function rates() public view returns (uint256, uint256[] memory); function convert(uint256 _amount, bytes32 _fromCurrency, bytes32 _toCurrency) public view returns (uint256); function defineCurrencies( bytes32[] memory _currencies, uint256[] memory _decimals, uint256 _rateOffset) public returns (bool); function defineRates(uint256[] memory _rates) public returns (bool); event RateOffset(uint256 rateOffset); event Currencies(bytes32[] currencies, uint256[] decimals); event Rate(bytes32 indexed currency, uint256 rate); } // File: contracts/tokensale/ChangeTokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title ChangeTokensale * @dev ChangeTokensale contract * * @author Cyril Lapinte - <[email protected]> * * Error messages * CTS01: message value must be positive * CTS02: No investment after currency change. */ contract ChangeTokensale is BaseTokensale { bytes32 internal baseCurrency_; IRatesProvider internal ratesProvider_; uint256 internal totalReceivedETH_; /* Investment */ function investETH() public payable { require(msg.value > 0, "CTS01"); totalReceivedETH_ = totalReceivedETH_.add(msg.value); Investor storage investor = investorInternal(msg.sender); uint256 amountETH = investor.unspentETH.add(msg.value); uint256 amountCurrency = ratesProvider_.convert(amountETH, "ETH", baseCurrency_); require(amountCurrency > 0, "CTS02"); investInternal(msg.sender, amountCurrency, false); } /** * @dev returns baseCurrency */ function baseCurrency() public view returns (bytes32) { return baseCurrency_; } /** * @dev returns ratesProvider */ function ratesProvider() public view returns (IRatesProvider) { return ratesProvider_; } /** * @dev returns totalRaisedETH */ function totalRaisedETH() public view returns (uint256) { return totalReceivedETH_.sub(totalUnspentETH_).sub(totalRefundedETH_); } /** * @dev returns totalReceivedETH */ function totalReceivedETH() public view returns (uint256) { return totalReceivedETH_; } /** * @dev add offchain investment */ function addOffchainInvestment(address _investor, uint256 _amount) public onlyOperator returns (bool) { investInternal(_investor, _amount, true); return true; } /** * @dev eval unspent ETH */ function evalUnspentETHInternal( Investor storage _investor, uint256 _invested ) internal view returns (uint256) { uint256 investedETH = ratesProvider_.convert(_invested, baseCurrency_, "ETH"); return super.evalUnspentETHInternal(_investor, investedETH); } } // File: contracts/interface/IUserRegistry.sol pragma solidity >=0.5.0 <0.6.0; /** * @title IUserRegistry * @dev IUserRegistry interface * @author Cyril Lapinte - <[email protected]> **/ contract IUserRegistry { event UserRegistered(uint256 indexed userId, address address_, uint256 validUntilTime); event AddressAttached(uint256 indexed userId, address address_); event AddressDetached(uint256 indexed userId, address address_); event UserSuspended(uint256 indexed userId); event UserRestored(uint256 indexed userId); event UserValidity(uint256 indexed userId, uint256 validUntilTime); event UserExtendedKey(uint256 indexed userId, uint256 key, uint256 value); event UserExtendedKeys(uint256 indexed userId, uint256[] values); event ExtendedKeysDefinition(uint256[] keys); function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime) external returns (bool); function registerManyUsersFullExternal( address[] calldata _addresses, uint256 _validUntilTime, uint256[] calldata _values) external returns (bool); function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses) external returns (bool); function detachManyAddressesExternal(address[] calldata _addresses) external returns (bool); function suspendManyUsersExternal(uint256[] calldata _userIds) external returns (bool); function restoreManyUsersExternal(uint256[] calldata _userIds) external returns (bool); function updateManyUsersExternal( uint256[] calldata _userIds, uint256 _validUntilTime, bool _suspended) external returns (bool); function updateManyUsersExtendedExternal( uint256[] calldata _userIds, uint256 _key, uint256 _value) external returns (bool); function updateManyUsersAllExtendedExternal( uint256[] calldata _userIds, uint256[] calldata _values) external returns (bool); function updateManyUsersFullExternal( uint256[] calldata _userIds, uint256 _validUntilTime, bool _suspended, uint256[] calldata _values) external returns (bool); function name() public view returns (string memory); function currency() public view returns (bytes32); function userCount() public view returns (uint256); function userId(address _address) public view returns (uint256); function validUserId(address _address) public view returns (uint256); function validUser(address _address, uint256[] memory _keys) public view returns (uint256, uint256[] memory); function validity(uint256 _userId) public view returns (uint256, bool); function extendedKeys() public view returns (uint256[] memory); function extended(uint256 _userId, uint256 _key) public view returns (uint256); function manyExtended(uint256 _userId, uint256[] memory _key) public view returns (uint256[] memory); function isAddressValid(address _address) public view returns (bool); function isValid(uint256 _userId) public view returns (bool); function defineExtendedKeys(uint256[] memory _extendedKeys) public returns (bool); function registerUser(address _address, uint256 _validUntilTime) public returns (bool); function registerUserFull( address _address, uint256 _validUntilTime, uint256[] memory _values) public returns (bool); function attachAddress(uint256 _userId, address _address) public returns (bool); function detachAddress(address _address) public returns (bool); function detachSelf() public returns (bool); function detachSelfAddress(address _address) public returns (bool); function suspendUser(uint256 _userId) public returns (bool); function restoreUser(uint256 _userId) public returns (bool); function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended) public returns (bool); function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value) public returns (bool); function updateUserAllExtended(uint256 _userId, uint256[] memory _values) public returns (bool); function updateUserFull( uint256 _userId, uint256 _validUntilTime, bool _suspended, uint256[] memory _values) public returns (bool); } // File: contracts/tokensale/UserTokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title UserTokensale * @dev UserTokensale contract * * @author Cyril Lapinte - <[email protected]> * * Error messages */ contract UserTokensale is ChangeTokensale { uint256[] public extendedKeys = [ 0, 1 ]; // KYC Level and AML Limit // Default investment based on the KYC Level. // Example [ 0, 300000, 1500000, 10000000, 100000000 ]; uint256[] internal contributionLimits_ = new uint256[](0); mapping(uint256 => Investor) internal investorIds; IUserRegistry internal userRegistry_; /** * @dev define contributionLimits */ function defineContributionLimits(uint256[] memory _contributionLimits) public onlyOperator returns (bool) { contributionLimits_ = _contributionLimits; emit ContributionLimits(_contributionLimits); return true; } /** * @dev contributionsLimit */ function contributionLimits() public view returns (uint256[] memory) { return contributionLimits_; } /** * @dev user registry */ function userRegistry() public view returns (IUserRegistry) { return userRegistry_; } function registredInvestorUnspentETH(uint256 _investorId) public view returns (uint256) { return investorIds[_investorId].unspentETH; } function registredInvestorInvested(uint256 _investorId) public view returns (uint256) { return investorIds[_investorId].invested; } function registredInvestorTokens(uint256 _investorId) public view returns (uint256) { return investorIds[_investorId].tokens; } function investorCount() public view returns (uint256) { return userRegistry_.userCount(); } /** * @dev contributionLimit */ function contributionLimit(uint256 _investorId) public view returns (uint256) { uint256 amlLimit = 0; uint256[] memory extended = userRegistry_.manyExtended(_investorId, extendedKeys); uint256 kycLevel = extended[0]; uint256 baseAmlLimit = extended[1]; if (baseAmlLimit > 0) { amlLimit = ratesProvider_.convert( baseAmlLimit, userRegistry_.currency(), baseCurrency_); } if (amlLimit == 0 && kycLevel < contributionLimits_.length) { amlLimit = contributionLimits_[kycLevel]; } return amlLimit.sub(investorIds[_investorId].invested); } /** * @dev tokenInvestment */ function tokenInvestment(address _investor, uint256 _amount) public view returns (uint256) { uint256 investorId = userRegistry_.validUserId(_investor); uint256 amlLimit = contributionLimit(investorId); return super.tokenInvestment(_investor, (_amount < amlLimit) ? _amount : amlLimit); } /** * @dev investor internal */ function investorInternal(address _investor) internal view returns (Investor storage) { return investorIds[userRegistry_.userId(_investor)]; } event ContributionLimits(uint256[] contributionLimits); } // File: contracts/Tokensale.sol pragma solidity >=0.5.0 <0.6.0; /** * @title Tokensale * @dev Tokensale contract * * @author Cyril Lapinte - <[email protected]> * * Error messages */ contract Tokensale is UserTokensale, BonusTokensale { /** * @dev constructor */ constructor( IERC20 _token, address _vaultERC20, address payable _vaultETH, uint256 _tokenPrice, uint256 _priceUnit, bytes32 _baseCurrency, IUserRegistry _userRegistry, IRatesProvider _ratesProvider, uint256 _start, uint256 _end ) public BonusTokensale(_token, _vaultERC20, _vaultETH, _tokenPrice, _priceUnit) { baseCurrency_ = _baseCurrency; userRegistry_ = _userRegistry; ratesProvider_ = _ratesProvider; updateSchedule(_start, _end); } }
fallback function/solhint-disable-next-line no-complex-fallback
function () external payable { require(msg.data.length == 0, "TOS03"); investETH(); }
12,886,903
// SPDX-License-Identifier: BUSL-1.1 // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {PercentageMath} from "../libraries/math/PercentageMath.sol"; import {WadRayMath} from "../libraries/math/WadRayMath.sol"; import {IInterestRateModel} from "../interfaces/IInterestRateModel.sol"; import {Constants} from "../libraries/helpers/Constants.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; /// @title Linear Interest Rate Model /// @notice Linear interest rate model, similar which Aave uses contract LinearInterestRateModel is IInterestRateModel { using PercentageMath for uint256; using SafeMath for uint256; using WadRayMath for uint256; // Uoptimal[0;1] in Wad uint256 public immutable _U_Optimal_WAD; // 1 - Uoptimal [0;1] x10.000, percentage plus two decimals uint256 public immutable _U_Optimal_inverted_WAD; // R_base in Ray uint256 public immutable _R_base_RAY; // R_Slope1 in Ray uint256 public immutable _R_slope1_RAY; // R_Slope2 in Ray uint256 public immutable _R_slope2_RAY; // Contract version uint constant public version = 1; /// @dev Constructor /// @param U_optimal Optimal U in percentage format: x10.000 - percentage plus two decimals /// @param R_base R_base in percentage format: x10.000 - percentage plus two decimals @param R_slope1 R_Slope1 in Ray /// @param R_slope1 R_Slope1 in percentage format: x10.000 - percentage plus two decimals /// @param R_slope2 R_Slope2 in percentage format: x10.000 - percentage plus two decimals constructor( uint256 U_optimal, uint256 R_base, uint256 R_slope1, uint256 R_slope2 ) { require( U_optimal <= PercentageMath.PERCENTAGE_FACTOR, Errors.INCORRECT_PARAMETER ); require( R_base <= PercentageMath.PERCENTAGE_FACTOR, Errors.INCORRECT_PARAMETER ); require( R_slope1 <= PercentageMath.PERCENTAGE_FACTOR, Errors.INCORRECT_PARAMETER ); // Convert percetns to WAD uint256 U_optimal_WAD = WadRayMath.WAD.percentMul(U_optimal); _U_Optimal_WAD = U_optimal_WAD; // 1 - Uoptimal in WAD _U_Optimal_inverted_WAD = WadRayMath.WAD.sub(U_optimal_WAD); _R_base_RAY = WadRayMath.RAY.percentMul(R_base); _R_slope1_RAY = WadRayMath.RAY.percentMul(R_slope1); _R_slope2_RAY = WadRayMath.RAY.percentMul(R_slope2); } /// @dev Calculated borrow rate based on expectedLiquidity and availableLiquidity /// @param expectedLiquidity Expected liquidity in the pool /// @param availableLiquidity Available liquidity in the pool function calcBorrowRate( uint256 expectedLiquidity, uint256 availableLiquidity ) external view override returns (uint256) { // Protection from direct sending tokens on PoolService account // T:[LR-5] // T:[LR-6] if (expectedLiquidity == 0 || expectedLiquidity < availableLiquidity) { return _R_base_RAY; } // expectedLiquidity - availableLiquidity // U = ------------------------------------- // expectedLiquidity uint256 U_WAD = (expectedLiquidity.sub(availableLiquidity)) .mul(WadRayMath.WAD) .div(expectedLiquidity); // if U < Uoptimal: // // U // borrowRate = Rbase + Rslope1 * ---------- // Uoptimal // if (U_WAD < _U_Optimal_WAD) { return _R_base_RAY.add(_R_slope1_RAY.mul(U_WAD).div(_U_Optimal_WAD)); } // if U >= Uoptimal: // // U - Uoptimal // borrowRate = Rbase + Rslope1 + Rslope2 * -------------- // 1 - Uoptimal return _R_base_RAY.add(_R_slope1_RAY).add( _R_slope2_RAY.mul(U_WAD.sub(_U_Optimal_WAD)).div( _U_Optimal_inverted_WAD ) ); // T:[LR-1,2,3] } /// @dev Gets model parameters /// @param U_optimal U_optimal in percentage format: [0;10,000] - percentage plus two decimals /// @param R_base R_base in RAY format /// @param R_slope1 R_slope1 in RAY format /// @param R_slope2 R_slope2 in RAY format function getModelParameters() external view returns ( uint256 U_optimal, uint256 R_base, uint256 R_slope1, uint256 R_slope2 ) { U_optimal = _U_Optimal_WAD.percentDiv(WadRayMath.WAD); // T:[LR-4] R_base = _R_base_RAY; // T:[LR-4] R_slope1 = _R_slope1_RAY; // T:[LR-4] R_slope2 = _R_slope2_RAY; // T:[LR-4] } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.7.4; import {Errors} from "../helpers/Errors.sol"; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; // T:[PM-1] } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[PM-1] return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; // T:[PM-1] } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[PM-2] uint256 halfPercentage = percentage / 2; // T:[PM-2] require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[PM-2] return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.7.4; import {Errors} from "../helpers/Errors.sol"; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) * More info https://github.com/aave/aave-protocol/blob/master/contracts/libraries/WadRayMath.sol */ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 */ function ray() internal pure returns (uint256) { return RAY; // T:[WRM-1] } /** * @return One wad, 1e18 */ function wad() internal pure returns (uint256) { return WAD; // T:[WRM-1] } /** * @return Half ray, 1e27/2 */ function halfRay() internal pure returns (uint256) { return halfRAY; // T:[WRM-2] } /** * @return Half ray, 1e18/2 */ function halfWad() internal pure returns (uint256) { return halfWAD; // T:[WRM-2] } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad */ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; // T:[WRM-3] } require( a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[WRM-3] return (a * b + halfWAD) / WAD; // T:[WRM-3] } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad */ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[WRM-4] uint256 halfB = b / 2; require( a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[WRM-4] return (a * WAD + halfB) / b; // T:[WRM-4] } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray */ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; // T:[WRM-5] } require( a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[WRM-5] return (a * b + halfRAY) / RAY; // T:[WRM-5] } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray */ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[WRM-6] uint256 halfB = b / 2; // T:[WRM-6] require( a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[WRM-6] return (a * RAY + halfB) / b; // T:[WRM-6] } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad */ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; // T:[WRM-7] uint256 result = halfRatio + a; // T:[WRM-7] require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); // T:[WRM-7] return result / WAD_RAY_RATIO; // T:[WRM-7] } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray */ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; // T:[WRM-8] require( result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW ); // T:[WRM-8] return result; // T:[WRM-8] } } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title IInterestRateModel interface /// @dev Interface for the calculation of the interest rates interface IInterestRateModel { /// @dev Calculated borrow rate based on expectedLiquidity and availableLiquidity /// @param expectedLiquidity Expected liquidity in the pool /// @param availableLiquidity Available liquidity in the pool function calcBorrowRate(uint256 expectedLiquidity, uint256 availableLiquidity) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; import {PercentageMath} from "../math/PercentageMath.sol"; library Constants { uint256 constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // 25% of MAX_INT uint256 constant MAX_INT_4 = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // REWARD FOR LEAN DEPLOYMENT MINING uint256 constant ACCOUNT_CREATION_REWARD = 1e5; uint256 constant DEPLOYMENT_COST = 1e17; // FEE = 10% uint256 constant FEE_INTEREST = 1000; // 10% // FEE + LIQUIDATION_FEE 2% uint256 constant FEE_LIQUIDATION = 200; // Liquidation premium 5% uint256 constant LIQUIDATION_DISCOUNTED_SUM = 9500; // 100% - LIQUIDATION_FEE - LIQUIDATION_PREMIUM uint256 constant UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD = LIQUIDATION_DISCOUNTED_SUM - FEE_LIQUIDATION; // Seconds in a year uint256 constant SECONDS_PER_YEAR = 365 days; uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = SECONDS_PER_YEAR * 3 /2; // 1e18 uint256 constant RAY = 1e27; uint256 constant WAD = 1e18; // OPERATIONS uint8 constant OPERATION_CLOSURE = 1; uint8 constant OPERATION_REPAY = 2; uint8 constant OPERATION_LIQUIDATION = 3; // Decimals for leverage, so x4 = 4*LEVERAGE_DECIMALS for openCreditAccount function uint8 constant LEVERAGE_DECIMALS = 100; // Maximum withdraw fee for pool in percentage math format. 100 = 1% uint8 constant MAX_WITHDRAW_FEE = 100; uint256 constant CHI_THRESHOLD = 9950; uint256 constant HF_CHECK_INTERVAL_DEFAULT = 4; uint256 constant NO_SWAP = 0; uint256 constant UNISWAP_V2 = 1; uint256 constant UNISWAP_V3 = 2; uint256 constant CURVE_V1 = 3; uint256 constant LP_YEARN = 4; uint256 constant EXACT_INPUT = 1; uint256 constant EXACT_OUTPUT = 2; } // SPDX-License-Identifier: GPL-2.0-or-later // Gearbox Protocol. Generalized leverage for DeFi protocols // (c) Gearbox Holdings, 2021 pragma solidity ^0.7.4; /// @title Errors library library Errors { // // COMMON // string public constant ZERO_ADDRESS_IS_NOT_ALLOWED = "Z0"; string public constant NOT_IMPLEMENTED = "NI"; string public constant INCORRECT_PATH_LENGTH = "PL"; string public constant INCORRECT_ARRAY_LENGTH = "CR"; string public constant REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY = "CP"; string public constant REGISTERED_POOLS_ONLY = "RP"; string public constant INCORRECT_PARAMETER = "IP"; // // MATH // string public constant MATH_MULTIPLICATION_OVERFLOW = "M1"; string public constant MATH_ADDITION_OVERFLOW = "M2"; string public constant MATH_DIVISION_BY_ZERO = "M3"; // // POOL // string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0"; string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1"; string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2"; string public constant POOL_INCORRECT_WITHDRAW_FEE = "PS3"; string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4"; // // CREDIT MANAGER // string public constant CM_NO_OPEN_ACCOUNT = "CM1"; string public constant CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT = "CM2"; string public constant CM_INCORRECT_AMOUNT = "CM3"; string public constant CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR = "CM4"; string public constant CM_CAN_UPDATE_WITH_SUCH_HEALTH_FACTOR = "CM5"; string public constant CM_WETH_GATEWAY_ONLY = "CM6"; string public constant CM_INCORRECT_PARAMS = "CM7"; string public constant CM_INCORRECT_FEES = "CM8"; string public constant CM_MAX_LEVERAGE_IS_TOO_HIGH = "CM9"; string public constant CM_CANT_CLOSE_WITH_LOSS = "CMA"; string public constant CM_TARGET_CONTRACT_iS_NOT_ALLOWED = "CMB"; string public constant CM_TRANSFER_FAILED = "CMC"; string public constant CM_INCORRECT_NEW_OWNER = "CME"; // // ACCOUNT FACTORY // string public constant AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK = "AF1"; string public constant AF_MINING_IS_FINISHED = "AF2"; string public constant AF_CREDIT_ACCOUNT_NOT_IN_STOCK = "AF3"; string public constant AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN = "AF4"; // // ADDRESS PROVIDER // string public constant AS_ADDRESS_NOT_FOUND = "AP1"; // // CONTRACTS REGISTER // string public constant CR_POOL_ALREADY_ADDED = "CR1"; string public constant CR_CREDIT_MANAGER_ALREADY_ADDED = "CR2"; // // CREDIT_FILTER // string public constant CF_UNDERLYING_TOKEN_FILTER_CONFLICT = "CF0"; string public constant CF_INCORRECT_LIQUIDATION_THRESHOLD = "CF1"; string public constant CF_TOKEN_IS_NOT_ALLOWED = "CF2"; string public constant CF_CREDIT_MANAGERS_ONLY = "CF3"; string public constant CF_ADAPTERS_ONLY = "CF4"; string public constant CF_OPERATION_LOW_HEALTH_FACTOR = "CF5"; string public constant CF_TOO_MUCH_ALLOWED_TOKENS = "CF6"; string public constant CF_INCORRECT_CHI_THRESHOLD = "CF7"; string public constant CF_INCORRECT_FAST_CHECK = "CF8"; string public constant CF_NON_TOKEN_CONTRACT = "CF9"; string public constant CF_CONTRACT_IS_NOT_IN_ALLOWED_LIST = "CFA"; string public constant CF_FAST_CHECK_NOT_COVERED_COLLATERAL_DROP = "CFB"; string public constant CF_SOME_LIQUIDATION_THRESHOLD_MORE_THAN_NEW_ONE = "CFC"; string public constant CF_ADAPTER_CAN_BE_USED_ONLY_ONCE = "CFD"; string public constant CF_INCORRECT_PRICEFEED = "CFE"; string public constant CF_TRANSFER_IS_NOT_ALLOWED = "CFF"; string public constant CF_CREDIT_MANAGER_IS_ALREADY_SET = "CFG"; // // CREDIT ACCOUNT // string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1"; string public constant CA_FACTORY_ONLY = "CA2"; // // PRICE ORACLE // string public constant PO_PRICE_FEED_DOESNT_EXIST = "PO0"; string public constant PO_TOKENS_WITH_DECIMALS_MORE_18_ISNT_ALLOWED = "PO1"; string public constant PO_AGGREGATOR_DECIMALS_SHOULD_BE_18 = "PO2"; // // ACL // string public constant ACL_CALLER_NOT_PAUSABLE_ADMIN = "ACL1"; string public constant ACL_CALLER_NOT_CONFIGURATOR = "ACL2"; // // WETH GATEWAY // string public constant WG_DESTINATION_IS_NOT_WETH_COMPATIBLE = "WG1"; string public constant WG_RECEIVE_IS_NOT_ALLOWED = "WG2"; string public constant WG_NOT_ENOUGH_FUNDS = "WG3"; // // LEVERAGED ACTIONS // string public constant LA_INCORRECT_VALUE = "LA1"; string public constant LA_HAS_VALUE_WITH_TOKEN_TRANSFER = "LA2"; string public constant LA_UNKNOWN_SWAP_INTERFACE = "LA3"; string public constant LA_UNKNOWN_LP_INTERFACE = "LA4"; string public constant LA_LOWER_THAN_AMOUNT_MIN = "LA5"; string public constant LA_TOKEN_OUT_IS_NOT_COLLATERAL = "LA6"; // // YEARN PRICE FEED // string public constant YPF_PRICE_PER_SHARE_OUT_OF_RANGE = "YP1"; string public constant YPF_INCORRECT_LIMITER_PARAMETERS = "YP2"; // // TOKEN DISTRIBUTOR // string public constant TD_WALLET_IS_ALREADY_CONNECTED_TO_VC = "TD1"; string public constant TD_INCORRECT_WEIGHTS = "TD2"; string public constant TD_NON_ZERO_BALANCE_AFTER_DISTRIBUTION = "TD3"; string public constant TD_CONTRIBUTOR_IS_NOT_REGISTERED = "TD4"; }
return One ray, 1e27/
function ray() internal pure returns (uint256) { }
1,278,491
pragma solidity ^0.4.18; import "./MarketBase.sol"; /** * @title MarketIdentity * @dev Contract used to determine unique identity of actors on protocol * NOTE: Each actor must be verified using some identity */ contract MarketIdentity is MarketBase { mapping (address => uint[]) repayments; mapping (address => uint[]) defaults; /** * @dev Retreives an array of repayments (and the size of each repayment) * for a particular borrower */ function getRepayments(address _address) public view returns (uint[]) { return repayments[_address]; } /** * @dev Retrieves an array of defaults (and the size of each default) * for a particular borrower */ function getDefaults(address _address) public view returns (uint[]) { return defaults[_address]; } /** * @dev Given the address, return the repayment at a specific index */ function getRepayment(address _address, uint _index) public view returns (uint) { return repayments[_address][_index]; } /** * @dev Given the address, return the default at a specific index */ function getDefault(address _address, uint _index) public view returns (uint) { return defaults[_address][_index]; } /** * @dev Retrieves the number of repayments */ function getRepaymentsLength(address _address) public view returns (uint) { return repayments[_address].length; } /** * @dev Retrieves the number of defaults */ function getDefaultsLength(address _address) public view returns (uint) { return defaults[_address].length; } }
Retrieves the number of repayments/
function getRepaymentsLength(address _address) public view returns (uint) { return repayments[_address].length; }
6,392,814
//SPDX License -- MIT pragma solidity ^0.8.5; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol"; //token address : 0xD4b86bb5BD81ef50Cd1ADA459a0833Aee09aF36b --deployed on ropsten test net contract TokenFactory is ERC20{ using SafeMath for uint256; address public owner; uint256 private _totalSupply; mapping(address => uint256) _balances; mapping(address => mapping(address=> uint256)) private _allowances; constructor () ERC20("Dummy Coin", "DC"){ owner = msg.sender; _totalSupply = 100000000 * 10 **decimals(); _balances[owner] = _totalSupply; } function decimals () public pure override returns(uint8){ return 2; } function totalSupply () public view override returns(uint256){ return _totalSupply; } function balanceOf(address account) public view override returns(uint256){ return _balances[account]; } function allowance(address owner, address spender) public view override returns(uint256){ return _allowances[owner][spender]; } function transfer (address recipient, uint256 amount) public override returns(bool){ require(_balances[msg.sender]>=amount , "Insufficient balance in sender's account"); _balances[msg.sender]=_balances[msg.sender].sub(amount); _balances[recipient]=_balances[recipient].add(amount); emit Transfer(msg.sender,recipient,amount); return true; } function approve (address recipient,uint256 amount) public override returns(bool){ // _approve(msg.sender,recipient,amount); // require(_balances[msg.sender]>= amount, "Insufficient balance in sender's account"); _allowances[msg.sender][recipient] = amount; emit Approval(msg.sender,recipient,amount); return true; } function transferFrom(address from, address to, uint256 amount) public override returns(bool){ /* uint256 currentAllowance = _allowances[sender][recipient]; require(_balances[sender] >= currentAllowance, "Insufficient balance in sender's account"); currentAllowance = currentAllowance.sub(amount); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender,recipient,amount); _allowances[sender][recipient] = currentAllowance; emit Approval(sender,recipient,amount);*/ _balances[from] = _balances[from].sub(amount); _allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount); _balances[to] = _balances[to].add(amount); emit Transfer(from, to, amount); return true; } }
_approve(msg.sender,recipient,amount); require(_balances[msg.sender]>= amount, "Insufficient balance in sender's account");
function approve (address recipient,uint256 amount) public override returns(bool){ _allowances[msg.sender][recipient] = amount; emit Approval(msg.sender,recipient,amount); return true; }
2,495,141
pragma solidity ^0.4.24; /* * Poexer.com is a real-time decentralized cryptocurrency exchange which allows you to trade Ethereum with POX tokens. * Buy, Sell, or Transfer POX tokens, fees of your transaction is used to pay earnings to other users holding POX tokens. * - The fee for Buying: 20% * - The fee for Selling: 10% * - The fee for Transfer: 10% * Reinvest or Withdraw your Ethereum earnings back from the exchange contract. * Poexer Referral Program: Log in to get your invitation link and share it with your friends! * Invite your friends to trade on Poexer.com, and you will receive up to 50% of the buy-in-fees they would otherwise pay to the contract, in ETH, in real-time! * References: POWH3D contract. */ contract POXToken { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> set new administrator // -> change the PoS difficulty (How many tokens it costs to hold a referral, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[(_customerAddress)]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "POXToken"; string public symbol = "POX"; uint8 constant public decimals = 18; uint8 constant internal buyFee_ = 20; uint8 constant internal sellFee_ = 10; uint8 constant internal exchangebuyFee_ = 2; uint8 constant internal exchangesellFee_ = 2; uint8 constant internal referralFeenormal_ = 8; uint8 constant internal referralFeedouble_ = 10; uint8 constant internal transferFee_ = 10; uint32 constant internal presaletransferFee_ = 1000000; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake Doubles Referral Rewards (defaults at 500 tokens) uint256 public stakingRequirement = 500e18; // presale mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1000 ether; uint256 constant internal ambassadorQuota_ = 1010 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // fees and measurement error address address private exchangefees; address private measurement; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function POXToken(address _exchangefees, address _measurement) public { require(_exchangefees != address(0)); exchangefees = _exchangefees; require(_measurement != address(0)); measurement = _measurement; // administrators administrators[0x7fb4ccc46fd1aa0396150d4ab671aede33a07812] = true; // pre-sale wallet. ambassadors_[0xf7544F23D93d08eB24376F49EaBBa50808b81849] = true; ambassadors_[0x6003B0f8f8d6E06F2ab100237f27fb3106308ae4] = true; ambassadors_[0x6766081E3a751C61bE43d82fe184f7C95F777885] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data // low fees for presale address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _feesEthereum = SafeMath.div(SafeMath.mul(_ethereum, exchangesellFee_), 100); uint256 _sellfeeEthereum = SafeMath.div(SafeMath.mul(_ethereum, sellFee_), 100); if (ambassadors_[_customerAddress] == true) { _sellfeeEthereum = SafeMath.div(_ethereum, exchangesellFee_); } uint256 _dividends = SafeMath.sub(_sellfeeEthereum, _feesEthereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _sellfeeEthereum); // fees and burn the sold tokens exchangefees.transfer(_feesEthereum); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token and measurement error profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); payoutsTo_[measurement] -= (int256) (SafeMath.sub((_dividends * magnitude), SafeMath.div((_dividends * magnitude), tokenSupply_) * tokenSupply_)); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders // low fees for presale uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); if (ambassadors_[_customerAddress] == true) { _tokenFee = SafeMath.div(_amountOfTokens, presaletransferFee_); } uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _feesEthereum = SafeMath.div(SafeMath.mul(tokensToEthereum_(_tokenFee), exchangebuyFee_), 100); uint256 _dividends = SafeMath.sub(tokensToEthereum_(_tokenFee), _feesEthereum); // fees and burn the fee tokens exchangefees.transfer(_feesEthereum); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders and measurement error profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); payoutsTo_[measurement] -= (int256) (SafeMath.sub((_dividends * magnitude), SafeMath.div((_dividends * magnitude), tokenSupply_) * tokenSupply_)); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the referral rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, sellFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, buyFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, buyFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, sellFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup and fees address _customerAddress = msg.sender; uint256 _feesEthereum = SafeMath.div(SafeMath.mul(_incomingEthereum, exchangebuyFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_incomingEthereum, referralFeenormal_), 100); // referral commission rewards to 40% for address that hold 500 POX or more if (tokenBalanceLedger_[_referredBy] >= stakingRequirement) { _referralBonus = SafeMath.div(SafeMath.mul(_incomingEthereum, referralFeedouble_), 100); } uint256 _dividends = SafeMath.sub((SafeMath.div(SafeMath.mul(_incomingEthereum, buyFee_), 100)), (SafeMath.add(_feesEthereum, _referralBonus))); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, (SafeMath.div(_incomingEthereum, 5))); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; exchangefees.transfer(_feesEthereum); // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a referral? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder // measurement error profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); payoutsTo_[measurement] -= (int256) (SafeMath.sub((_dividends * magnitude), SafeMath.div((_dividends * magnitude), tokenSupply_) * tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // measurement error payoutsTo_[measurement] -= (int256) (SafeMath.sub(SafeMath.sub(_taxedEthereum, SafeMath.div(SafeMath.mul(_taxedEthereum, sellFee_), 100)), SafeMath.sub(tokensToEthereum_(_amountOfTokens), SafeMath.div(SafeMath.mul(tokensToEthereum_(_amountOfTokens), sellFee_), 100))) * magnitude); // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper * with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Function for the frontend to dynamically retrieve the price scaling of buy orders./
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, buyFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; }
10,487,219
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "./Erc721Interface.sol"; /** * @title Darilka * @dev Contract designed to make both centralized & decentralized checks * 1) centralized to check if receiver is good * 2) decentralized to not trust to this contract owner */ contract Darilka { address public owner; uint256 public commission; uint256 public amountForReceiver; /** * @dev Modifier to check if caller is owner. */ modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == owner, "Caller is not owner"); _; } struct NFT { address nftContract; uint256 tokenId; } mapping(bytes32 => bytes32) private confirmationHashes; mapping(bytes32 => address) private bookedTransfer; /** * @dev Set contract deployer as owner */ constructor(uint256 _commission, uint256 _amountForReceiver) { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor commission = _commission; amountForReceiver = _amountForReceiver; } /** * @dev Change owner * @param newOwner address of new owner */ function setOwner(address newOwner) public isOwner { owner = newOwner; } function setCommission(uint256 newCommission) public isOwner { commission = newCommission; } function setAmountForReceiver(uint256 newAmountForReceiver) public isOwner { amountForReceiver = newAmountForReceiver; } function withdraw() external payable isOwner { payable(owner).transfer(address(this).balance); } /** * @dev Store confirmation hash to make nft transaction * @param nftContract address of nft which will be allowed to transfer * @param tokenId uint256 nft order id in contract */ function setConfirmation(address nftContract, uint256 tokenId, bytes32 keccak256ConfirmationHash) payable public { require(msg.value >= commission + amountForReceiver, "Expect collateral not less than commission + amountForReceiver"); require(Erc721Interface(nftContract).ownerOf(tokenId) == msg.sender, "Only nft owner could set confirmation password hash"); confirmationHashes[keccak256(abi.encodePacked(nftContract, tokenId))] = keccak256ConfirmationHash; } /** * book delegated transfer: call this on backend after get centralized confirmation from receiver * make two things: book transfer for receiver address and send some money to run transfer */ function bookTransfer(address receiver, address nftContract, uint256 tokenId) payable public isOwner { bookedTransfer[keccak256(abi.encodePacked(nftContract, tokenId))] = receiver; payable(receiver).transfer(amountForReceiver); } /** * performTransferNFT with confirmation, it needed to not trust our backend **/ function performTransferNFT(address sender, address receiver, address nftContract, uint256 tokenId, string memory confirmation) public { bytes32 nft = keccak256(abi.encodePacked(nftContract, tokenId)); require(bookedTransfer[nft] == msg.sender); require(confirmationHashes[nft] == keccak256(abi.encodePacked(confirmation))); Erc721Interface(nftContract).safeTransferFrom(sender, receiver, tokenId); delete confirmationHashes[nft]; delete bookedTransfer[nft]; } }
Change owner newOwner address of new owner/
function setOwner(address newOwner) public isOwner { owner = newOwner; }
14,038,335
pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import "./utils/Deployer.sol"; import "./interfaces/IERC721Template.sol"; import "OpenZeppelin/[email protected]//contracts/access/Ownable.sol"; import "./interfaces/IERC20Template.sol"; /** * @title DTFactory contract * @author Ocean Protocol Team * * @dev Implementation of Ocean DataTokens Factory * * DTFactory deploys DataToken proxy contracts. * New DataToken proxy contracts are links to the template contract's bytecode. * Proxy contract functionality is based on Ocean Protocol custom implementation of ERC1167 standard. */ contract ERC721Factory is Deployer, Ownable { address private communityFeeCollector; uint256 private currentNFTCount; address private erc20Factory; uint256 private nftTemplateCount; struct Template { address templateAddress; bool isActive; } mapping(uint256 => Template) public nftTemplateList; mapping(uint256 => Template) public templateList; mapping(address => address) public erc721List; mapping(address => bool) public erc20List; event NFTCreated( address indexed newTokenAddress, address indexed templateAddress, string tokenName, address admin, string symbol, string tokenURI ); uint256 private currentTokenCount = 0; uint256 public templateCount; address public router; event Template721Added(address indexed _templateAddress, uint256 indexed nftTemplateCount); event Template20Added(address indexed _templateAddress, uint256 indexed nftTemplateCount); //stored here only for ABI reasons event TokenCreated( address indexed newTokenAddress, address indexed templateAddress, string name, string symbol, uint256 cap, address creator ); event NewPool( address poolAddress, address ssContract, address basetokenAddress ); event NewFixedRate(bytes32 exchangeId, address owner); event DispenserCreated( // emited when a dispenser is created address indexed datatokenAddress, address indexed owner, uint256 maxTokens, uint256 maxBalance, address allowedSwapper ); /** * @dev constructor * Called on contract deployment. Could not be called with zero address parameters. * @param _template refers to the address of a deployed DataToken contract. * @param _collector refers to the community fee collector address * @param _router router contract address */ constructor( address _template721, address _template, address _collector, address _router ) { require( _template != address(0) && _collector != address(0) && _template721 != address(0), "ERC721DTFactory: Invalid template token/community fee collector address" ); add721TokenTemplate(_template721); addTokenTemplate(_template); router = _router; communityFeeCollector = _collector; } /** * @dev deployERC721Contract * * @param name NFT name * @param symbol NFT Symbol * @param _templateIndex template index we want to use * @param additionalERC20Deployer if != address(0), we will add it with ERC20Deployer role */ function deployERC721Contract( string memory name, string memory symbol, uint256 _templateIndex, address additionalERC20Deployer, string memory tokenURI ) public returns (address token) { require( _templateIndex <= nftTemplateCount && _templateIndex != 0, "ERC721DTFactory: Template index doesnt exist" ); Template memory tokenTemplate = nftTemplateList[_templateIndex]; require( tokenTemplate.isActive == true, "ERC721DTFactory: ERC721Token Template disabled" ); token = deploy(tokenTemplate.templateAddress); require( token != address(0), "ERC721DTFactory: Failed to perform minimal deploy of a new token" ); erc721List[token] = token; IERC721Template tokenInstance = IERC721Template(token); require( tokenInstance.initialize( msg.sender, name, symbol, address(this), additionalERC20Deployer, tokenURI ), "ERC721DTFactory: Unable to initialize token instance" ); emit NFTCreated(token, tokenTemplate.templateAddress, name, msg.sender, symbol, tokenURI); currentNFTCount += 1; } /** * @dev get the current token count. * @return the current token count */ function getCurrentNFTCount() external view returns (uint256) { return currentNFTCount; } /** * @dev get the token template Object * @param _index template Index * @return the template struct */ function getNFTTemplate(uint256 _index) external view returns (Template memory) { Template memory template = nftTemplateList[_index]; return template; } /** * @dev add a new NFT Template. Only Factory Owner can call it * @param _templateAddress new template address * @return the actual template count */ function add721TokenTemplate(address _templateAddress) public onlyOwner returns (uint256) { require( _templateAddress != address(0), "ERC721DTFactory: ERC721 template address(0) NOT ALLOWED" ); require(isContract(_templateAddress), "ERC721Factory: NOT CONTRACT"); nftTemplateCount += 1; Template memory template = Template(_templateAddress, true); nftTemplateList[nftTemplateCount] = template; emit Template721Added(_templateAddress,nftTemplateCount); return nftTemplateCount; } /** * @dev reactivate a disabled NFT Template. Only Factory Owner can call it * @param _index index we want to reactivate */ // function to activate a disabled token. function reactivate721TokenTemplate(uint256 _index) external onlyOwner { require( _index <= nftTemplateCount && _index != 0, "ERC721DTFactory: Template index doesnt exist" ); Template storage template = nftTemplateList[_index]; template.isActive = true; } /** * @dev disable an NFT Template. Only Factory Owner can call it * @param _index index we want to disable */ function disable721TokenTemplate(uint256 _index) external onlyOwner { require( _index <= nftTemplateCount && _index != 0, "ERC721DTFactory: Template index doesnt exist" ); Template storage template = nftTemplateList[_index]; template.isActive = false; } function getCurrentNFTTemplateCount() external view returns (uint256) { return nftTemplateCount; } /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } struct tokenStruct{ string[] strings; address[] addresses; uint256[] uints; bytes[] bytess; address owner; } /** * @dev Deploys new DataToken proxy contract. * This function is not called directly from here. It's called from the NFT contract. An NFT contract can deploy multiple ERC20 tokens. * @param _templateIndex ERC20Template index * @param strings refers to an array of strings * [0] = name * [1] = symbol * @param addresses refers to an array of addresses * [0] = minter account who can mint datatokens (can have multiple minters) * [1] = feeManager initial feeManager for this DT * [2] = publishing Market Address * [3] = publishing Market Fee Token * @param uints refers to an array of uints * [0] = cap_ the total ERC20 cap * [1] = publishing Market Fee Amount * @param bytess refers to an array of bytes, not in use now, left for future templates * @return token address of a new proxy DataToken contract */ function createToken( uint256 _templateIndex, string[] memory strings, address[] memory addresses, uint256[] memory uints, bytes[] memory bytess ) public returns (address token) { require( erc721List[msg.sender] == msg.sender, "ERC721Factory: ONLY ERC721 INSTANCE FROM ERC721FACTORY" ); token = _createToken(_templateIndex, strings, addresses, uints, bytess, msg.sender); } function _createToken( uint256 _templateIndex, string[] memory strings, address[] memory addresses, uint256[] memory uints, bytes[] memory bytess, address owner ) internal returns (address token) { require(uints[0] != 0, "ERC20Factory: zero cap is not allowed"); require( _templateIndex <= templateCount && _templateIndex != 0, "ERC20Factory: Template index doesnt exist" ); Template memory tokenTemplate = templateList[_templateIndex]; require( tokenTemplate.isActive == true, "ERC20Factory: ERC721Token Template disabled" ); token = deploy(tokenTemplate.templateAddress); erc20List[token] = true; require( token != address(0), "ERC721Factory: Failed to perform minimal deploy of a new token" ); emit TokenCreated(token, tokenTemplate.templateAddress, strings[0], strings[1], uints[0], owner); currentTokenCount += 1; tokenStruct memory tokenData; tokenData.strings = strings; tokenData.addresses = addresses; tokenData.uints = uints; tokenData.owner = owner; tokenData.bytess = bytess; _createTokenStep2(token, tokenData); } function _createTokenStep2(address token, tokenStruct memory tokenData) internal { IERC20Template tokenInstance = IERC20Template(token); address[] memory factoryAddresses = new address[](3); factoryAddresses[0] = tokenData.owner; factoryAddresses[1] = communityFeeCollector; factoryAddresses[2] = router; require( tokenInstance.initialize( tokenData.strings, tokenData.addresses, factoryAddresses, tokenData.uints, tokenData.bytess ), "ERC20Factory: Unable to initialize token instance" ); } /** * @dev get the current ERC20token deployed count. * @return the current token count */ function getCurrentTokenCount() external view returns (uint256) { return currentTokenCount; } /** * @dev get the current ERC20token template. @param _index template Index * @return the token Template Object */ function getTokenTemplate(uint256 _index) external view returns (Template memory) { Template memory template = templateList[_index]; require( _index <= templateCount && _index != 0, "ERC20Factory: Template index doesnt exist" ); return template; } /** * @dev add a new ERC20Template. Only Factory Owner can call it * @param _templateAddress new template address * @return the actual template count */ function addTokenTemplate(address _templateAddress) public onlyOwner returns (uint256) { require( _templateAddress != address(0), "ERC20Factory: ERC721 template address(0) NOT ALLOWED" ); require(isContract(_templateAddress), "ERC20Factory: NOT CONTRACT"); templateCount += 1; Template memory template = Template(_templateAddress, true); templateList[templateCount] = template; emit Template20Added(_templateAddress, templateCount); return templateCount; } /** * @dev disable an ERC20Template. Only Factory Owner can call it * @param _index index we want to disable */ function disableTokenTemplate(uint256 _index) external onlyOwner { Template storage template = templateList[_index]; template.isActive = false; } /** * @dev reactivate a disabled ERC20Template. Only Factory Owner can call it * @param _index index we want to reactivate */ // function to activate a disabled token. function reactivateTokenTemplate(uint256 _index) external onlyOwner { require( _index <= templateCount && _index != 0, "ERC20DTFactory: Template index doesnt exist" ); Template storage template = templateList[_index]; template.isActive = true; } // if templateCount is public we could remove it, or set templateCount to private function getCurrentTemplateCount() external view returns (uint256) { return templateCount; } struct tokenOrder { address tokenAddress; address consumer; uint256 amount; uint256 serviceId; address consumeFeeAddress; address consumeFeeToken; // address of the token marketplace wants to add fee on top uint256 consumeFeeAmount; } /** * @dev startMultipleTokenOrder * Used as a proxy to order multiple services * Users can have inifinite approvals for fees for factory instead of having one approval/ erc20 contract * Requires previous approval of all : * - consumeFeeTokens * - publishMarketFeeTokens * - erc20 datatokens * @param orders an array of struct tokenOrder */ function startMultipleTokenOrder( tokenOrder[] memory orders ) external { uint256 ids = orders.length; // TO DO. We can do better here , by groupping publishMarketFeeTokens and consumeFeeTokens and have a single // transfer for each one, instead of doing it per dt.. for (uint256 i = 0; i < ids; i++) { (address publishMarketFeeAddress, address publishMarketFeeToken, uint256 publishMarketFeeAmount) = IERC20Template(orders[i].tokenAddress).getPublishingMarketFee(); // check if we have publishFees, if so transfer them to us and approve dttemplate to take them if (publishMarketFeeAmount > 0 && publishMarketFeeToken!=address(0) && publishMarketFeeAddress!=address(0)) { require(IERC20Template(publishMarketFeeToken).transferFrom( msg.sender, address(this), publishMarketFeeAmount ),'Failed to transfer publishFee'); IERC20Template(publishMarketFeeToken).approve(orders[i].tokenAddress, publishMarketFeeAmount); } // check if we have consumeFees, if so transfer them to us and approve dttemplate to take them if (orders[i].consumeFeeAmount > 0 && orders[i].consumeFeeToken!=address(0) && orders[i].consumeFeeAddress!=address(0)) { require(IERC20Template(orders[i].consumeFeeToken).transferFrom( msg.sender, address(this), orders[i].consumeFeeAmount ),'Failed to transfer consumeFee'); IERC20Template(orders[i].consumeFeeToken).approve(orders[i].tokenAddress, orders[i].consumeFeeAmount); } // transfer erc20 datatoken from consumer to us require(IERC20Template(orders[i].tokenAddress).transferFrom( msg.sender, address(this), orders[i].amount ),'Failed to transfer datatoken'); IERC20Template(orders[i].tokenAddress).startOrder( orders[i].consumer, orders[i].amount, orders[i].serviceId, orders[i].consumeFeeAddress, orders[i].consumeFeeToken, orders[i].consumeFeeAmount ); } } // helper functions to save number of transactions struct NftCreateData{ string name; string symbol; uint256 templateIndex; string tokenURI; } struct ErcCreateData{ uint256 templateIndex; string[] strings; address[] addresses; uint256[] uints; bytes[] bytess; } /** * @dev createNftWithErc * Creates a new NFT, then a ERC20,all in one call * @param _NftCreateData input data for nft creation * @param _ErcCreateData input data for erc20 creation */ function createNftWithErc( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData ) external returns (address erc721Address, address erc20Address){ erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(0), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); } struct PoolData{ address[] addresses; uint256[] ssParams; uint256[] swapFees; } /** * @dev createNftErcWithPool * Creates a new NFT, then a ERC20, then a Pool, all in one call * Use this carefully, because if Pool creation fails, you are still going to pay a lot of gas * @param _NftCreateData input data for NFT Creation * @param _ErcCreateData input data for ERC20 Creation * @param _PoolData input data for Pool Creation */ function createNftErcWithPool( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, PoolData calldata _PoolData ) external returns (address erc721Address, address erc20Address, address poolAddress){ require(IERC20Template(_PoolData.addresses[1]).transferFrom( msg.sender, address(this), _PoolData.ssParams[4] ),'Failed to transfer initial pool basetoken liquidity'); //we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the pool erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); // allow router to take the liquidity IERC20Template(_PoolData.addresses[1]).approve(router,_PoolData.ssParams[4]); poolAddress = IERC20Template(erc20Address).deployPool( _PoolData.ssParams, _PoolData.swapFees, _PoolData.addresses ); } struct FixedData{ address fixedPriceAddress; address[] addresses; uint256[] uints; } /** * @dev createNftErcWithFixedRate * Creates a new NFT, then a ERC20, then a FixedRateExchange, all in one call * Use this carefully, because if Fixed Rate creation fails, you are still going to pay a lot of gas * @param _NftCreateData input data for NFT Creation * @param _ErcCreateData input data for ERC20 Creation * @param _FixedData input data for FixedRate Creation */ function createNftErcWithFixedRate( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, FixedData calldata _FixedData ) external returns (address erc721Address, address erc20Address, bytes32 exchangeId){ //we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the fixedrate erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); exchangeId = IERC20Template(erc20Address).createFixedRate( _FixedData.fixedPriceAddress, _FixedData.addresses, _FixedData.uints ); } struct DispenserData{ address dispenserAddress; uint256 maxTokens; uint256 maxBalance; bool withMint; address allowedSwapper; } /** * @dev createNftErcWithDispenser * Creates a new NFT, then a ERC20, then a Dispenser, all in one call * Use this carefully * @param _NftCreateData input data for NFT Creation * @param _ErcCreateData input data for ERC20 Creation * @param _DispenserData input data for Dispenser Creation */ function createNftErcWithDispenser( NftCreateData calldata _NftCreateData, ErcCreateData calldata _ErcCreateData, DispenserData calldata _DispenserData ) external returns (address erc721Address, address erc20Address){ //we are adding ourselfs as a ERC20 Deployer, because we need it in order to deploy the fixedrate erc721Address = deployERC721Contract( _NftCreateData.name, _NftCreateData.symbol, _NftCreateData.templateIndex, address(this), _NftCreateData.tokenURI); erc20Address = _createToken( _ErcCreateData.templateIndex, _ErcCreateData.strings, _ErcCreateData.addresses, _ErcCreateData.uints, _ErcCreateData.bytess, erc721Address); IERC20Template(erc20Address).createDispenser( _DispenserData.dispenserAddress, _DispenserData.maxTokens, _DispenserData.maxBalance, _DispenserData.withMint, _DispenserData.allowedSwapper ); } }
get the current token count. return the current token count/
function getCurrentNFTCount() external view returns (uint256) { return currentNFTCount; }
12,786,031
./full_match/4/0x01cb65a2C42131E5DBF72136321db610432C1890/sources/contracts/h2_List_Student.sol
SPDX-License-Identifier: MIT
interface StudentsInterface { function getStudentsList() external view returns (string[] memory studentsList); pragma solidity >=0.7.0 <0.9.0; }
12,410,813
// SPDX-Licene-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./libraries/DecimalsConverter.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IShieldMining.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./interfaces/IPolicyBookAdmin.sol"; import "./interfaces/IPolicyBookFacade.sol"; import "./interfaces/helpers/IPriceFeed.sol"; import "./interfaces/IPolicyBookFabric.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract PolicyBookFacade is IPolicyBookFacade, AbstractDependant, Initializable { using EnumerableSet for EnumerableSet.AddressSet; using Math for uint256; IPolicyBookAdmin public policyBookAdmin; ILeveragePortfolio public reinsurancePool; IPolicyBook public override policyBook; IShieldMining public shieldMining; IPolicyBookRegistry public policyBookRegistry; using SafeMath for uint256; ILiquidityRegistry public liquidityRegistry; address public capitalPoolAddress; address public priceFeed; // virtual funds deployed by reinsurance pool uint256 public override VUreinsurnacePool; // leverage funds deployed by reinsurance pool uint256 public override LUreinsurnacePool; // leverage funds deployed by user leverage pool mapping(address => uint256) public override LUuserLeveragePool; // total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) uint256 public override totalLeveragedLiquidity; uint256 public override userleveragedMPL; uint256 public override reinsurancePoolMPL; uint256 public override rebalancingThreshold; bool public override safePricingModel; mapping(address => uint256) public override userLiquidity; EnumerableSet.AddressSet internal userLeveragePools; event DeployLeverageFunds(uint256 _deployedAmount); modifier onlyCapitalPool() { require(msg.sender == capitalPoolAddress, "PBFC: only CapitalPool"); _; } modifier onlyPolicyBookAdmin() { require(msg.sender == address(policyBookAdmin), "PBFC: Not a PBA"); _; } modifier onlyLeveragePortfolio() { require( msg.sender == address(reinsurancePool) || policyBookRegistry.isUserLeveragePool(msg.sender), "PBFC: only LeveragePortfolio" ); _; } modifier onlyPolicyBookRegistry() { require(msg.sender == address(policyBookRegistry), "PBFC: Not a policy book registry"); _; } function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 _initialDeposit ) external override initializer { policyBook = IPolicyBook(pbProxy); rebalancingThreshold = DEFAULT_REBALANCING_THRESHOLD; userLiquidity[liquidityProvider] = _initialDeposit; } function setDependencies(IContractsRegistry contractsRegistry) external override onlyInjectorOrZero { IContractsRegistry _contractsRegistry = IContractsRegistry(contractsRegistry); capitalPoolAddress = _contractsRegistry.getCapitalPoolContract(); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); policyBookAdmin = IPolicyBookAdmin(_contractsRegistry.getPolicyBookAdminContract()); priceFeed = _contractsRegistry.getPriceFeedContract(); reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract()); shieldMining = IShieldMining(_contractsRegistry.getShieldMiningContract()); } /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber is number of seconds to cover /// @param _coverTokens is number of tokens to cover function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external override { _buyPolicy(msg.sender, msg.sender, _epochsNumber, _coverTokens, 0, address(0)); } function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external override { _buyPolicy(msg.sender, _holder, _epochsNumber, _coverTokens, 0, address(0)); } function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external override { uint256 _distributorFee = policyBookAdmin.distributorFees(_distributor); _buyPolicy( msg.sender, msg.sender, _epochsNumber, _coverTokens, _distributorFee, _distributor ); } /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _holder address user the policy is being "bought for" /// @param _epochsNumber is number of seconds to cover /// @param _coverTokens is number of tokens to cover function buyPolicyFromDistributorFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external override { uint256 _distributorFee = policyBookAdmin.distributorFees(_distributor); _buyPolicy( msg.sender, _holder, _epochsNumber, _coverTokens, _distributorFee, _distributor ); } /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external override { _addLiquidity(msg.sender, msg.sender, _liquidityAmount, 0); } function addLiquidityFromDistributorFor(address _liquidityHolderAddr, uint256 _liquidityAmount) external override { _addLiquidity(msg.sender, _liquidityHolderAddr, _liquidityAmount, 0); } /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external override { _addLiquidity(msg.sender, msg.sender, _liquidityAmount, _stakeSTBLAmount); } function _addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) internal { uint256 _tokensToAdd = policyBook.addLiquidity( _liquidityBuyerAddr, _liquidityHolderAddr, _liquidityAmount, _stakeSTBLAmount ); _reevaluateProvidedLeverageStable(_liquidityAmount); _updateShieldMining(_liquidityHolderAddr, _tokensToAdd, false); } function _buyPolicy( address _policyBuyerAddr, address _policyHolderAddr, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) internal { (uint256 _premium, ) = policyBook.buyPolicy( _policyBuyerAddr, _policyHolderAddr, _epochsNumber, _coverTokens, _distributorFee, _distributor ); _reevaluateProvidedLeverageStable(_premium); } function _reevaluateProvidedLeverageStable(uint256 newAmount) internal { uint256 _newAmountPercentage; uint256 _totalLiq = policyBook.totalLiquidity(); if (_totalLiq > 0) { _newAmountPercentage = newAmount.mul(PERCENTAGE_100).div(_totalLiq); } if ((_totalLiq > 0 && _newAmountPercentage > rebalancingThreshold) || _totalLiq == 0) { _deployLeveragedFunds(); } } /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external override onlyLeveragePortfolio { if (leveragePool == ILeveragePortfolio.LeveragePortfolio.USERLEVERAGEPOOL) { LUuserLeveragePool[msg.sender] = deployedAmount; LUuserLeveragePool[msg.sender] > 0 ? userLeveragePools.add(msg.sender) : userLeveragePools.remove(msg.sender); } else { LUreinsurnacePool = deployedAmount; } uint256 _LUuserLeveragePool; for (uint256 i = 0; i < userLeveragePools.length(); i++) { _LUuserLeveragePool += LUuserLeveragePool[userLeveragePools.at(i)]; } totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add( _LUuserLeveragePool ); emit DeployLeverageFunds(deployedAmount); } /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external override onlyLeveragePortfolio { VUreinsurnacePool = deployedAmount; uint256 _LUuserLeveragePool; if (userLeveragePools.length() > 0) { _LUuserLeveragePool = LUuserLeveragePool[userLeveragePools.at(0)]; } totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add( _LUuserLeveragePool ); emit DeployLeverageFunds(deployedAmount); } function _deployLeveragedFunds() internal { uint256 _deployedAmount; uint256 _LUuserLeveragePool; _deployedAmount = reinsurancePool.deployVirtualStableToCoveragePools(); VUreinsurnacePool = _deployedAmount; _deployedAmount = reinsurancePool.deployLeverageStableToCoveragePools( ILeveragePortfolio.LeveragePortfolio.REINSURANCEPOOL ); LUreinsurnacePool = _deployedAmount; address[] memory _userLeverageArr = policyBookRegistry.listByType( IPolicyBookFabric.ContractType.VARIOUS, 0, policyBookRegistry.countByType(IPolicyBookFabric.ContractType.VARIOUS) ); for (uint256 i = 0; i < _userLeverageArr.length; i++) { _deployedAmount = ILeveragePortfolio(_userLeverageArr[i]) .deployLeverageStableToCoveragePools( ILeveragePortfolio.LeveragePortfolio.USERLEVERAGEPOOL ); LUuserLeveragePool[_userLeverageArr[i]] = _deployedAmount; _deployedAmount > 0 ? userLeveragePools.add(_userLeverageArr[i]) : userLeveragePools.remove(_userLeverageArr[i]); _LUuserLeveragePool += _deployedAmount; } totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add( _LUuserLeveragePool ); } function _updateShieldMining( address liquidityProvider, uint256 liquidityAmount, bool isWithdraw ) internal { // check if SM active if (shieldMining.getShieldTokenAddress(address(policyBook)) != address(0)) { shieldMining.updateTotalSupply(address(policyBook), address(0), liquidityProvider); } if (isWithdraw) { userLiquidity[liquidityProvider] -= liquidityAmount; } else { userLiquidity[liquidityProvider] += liquidityAmount; } } /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external override { uint256 _withdrawAmount = policyBook.withdrawLiquidity(msg.sender); _reevaluateProvidedLeverageStable(_withdrawAmount); _updateShieldMining(msg.sender, _withdrawAmount, true); } /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external override onlyPolicyBookAdmin { userleveragedMPL = _userLeverageMPL; reinsurancePoolMPL = _reinsuranceLeverageMPL; } /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external override onlyPolicyBookAdmin { require(_newRebalancingThreshold > 0, "PBF: threshold can not be 0"); rebalancingThreshold = _newRebalancingThreshold; } /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external override onlyPolicyBookAdmin { safePricingModel = _safePricingModel; } /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view override returns ( uint256, uint256, uint256, address ) { uint256 _LUuserLeveragePool; address _userLeverageAddress; if (userLeveragePools.length() > 0) { _LUuserLeveragePool = DecimalsConverter.convertFrom18( LUuserLeveragePool[userLeveragePools.at(0)], policyBook.stblDecimals() ); _userLeverageAddress = userLeveragePools.at(0); } return ( DecimalsConverter.convertFrom18(VUreinsurnacePool, policyBook.stblDecimals()), DecimalsConverter.convertFrom18(LUreinsurnacePool, policyBook.stblDecimals()), _LUuserLeveragePool, _userLeverageAddress ); } // TODO possible sandwich attack or allowance fluctuation function getClaimApprovalAmount(address user) external view override returns (uint256) { (uint256 _coverTokens, , , , ) = policyBook.policyHolders(user); _coverTokens = DecimalsConverter.convertFrom18( _coverTokens.div(100), policyBook.stblDecimals() ); return IPriceFeed(priceFeed).howManyBMIsInUSDT(_coverTokens); } /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external override { IPolicyBook.WithdrawalStatus _withdrawlStatus = policyBook.getWithdrawalStatus(msg.sender); require( _withdrawlStatus == IPolicyBook.WithdrawalStatus.NONE || _withdrawlStatus == IPolicyBook.WithdrawalStatus.EXPIRED, "PBf: ongoing withdrawl request" ); policyBook.requestWithdrawal(_tokensToWithdraw, msg.sender); liquidityRegistry.registerWithdrawl(address(policyBook), msg.sender); } /// @notice Used to get a list of user leverage pools which provide leverage to this pool , use with count() /// @return _userLeveragePools a list containing policybook addresses function listUserLeveragePools(uint256 offset, uint256 limit) external view override returns (address[] memory _userLeveragePools) { uint256 to = (offset.add(limit)).min(userLeveragePools.length()).max(offset); _userLeveragePools = new address[](to - offset); for (uint256 i = offset; i < to; i++) { _userLeveragePools[i - offset] = userLeveragePools.at(i); } } /// @notice get count of user leverage pools which provide leverage to this pool function countUserLeveragePools() external view override returns (uint256) { return userLeveragePools.length(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice the intention of this library is to be able to easily convert /// one amount of tokens with N decimal places /// to another amount with M decimal places library DecimalsConverter { using SafeMath for uint256; function convert( uint256 amount, uint256 baseDecimals, uint256 destinationDecimals ) internal pure returns (uint256) { if (baseDecimals > destinationDecimals) { amount = amount.div(10**(baseDecimals - destinationDecimals)); } else if (baseDecimals < destinationDecimals) { amount = amount.mul(10**(destinationDecimals - baseDecimals)); } return amount; } function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) { return convert(amount, baseDecimals, 18); } function convertFrom18(uint256 amount, uint256 destinationDecimals) internal pure returns (uint256) { return convert(amount, 18, destinationDecimals); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPriceFeed { function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256); function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IShieldMining { struct ShieldMiningInfo { IERC20 rewardsToken; uint8 decimals; uint256 firstBlockWithReward; uint256 lastBlockWithReward; uint256 lastUpdateBlock; uint256 rewardTokensLocked; uint256 rewardPerTokenStored; uint256 totalSupply; uint256[] endsOfDistribution; // new state post v2 uint256 nearestLastBlocksWithReward; // lastBlockWithReward => rewardPerBlock mapping(uint256 => uint256) rewardPerBlock; } struct ShieldMiningDeposit { address policyBook; uint256 amount; uint256 duration; uint256 depositRewardPerBlock; uint256 startBlock; uint256 endBlock; } /// TODO document SM functions function blocksWithRewardsPassed(address _policyBook) external view returns (uint256); function rewardPerToken(address _policyBook) external view returns (uint256); function earned( address _policyBook, address _userLeveragePool, address _account ) external view returns (uint256); function updateTotalSupply( address _policyBook, address _userLeveragePool, address liquidityProvider ) external; function associateShieldMining(address _policyBook, address _shieldMiningToken) external; function fillShieldMining( address _policyBook, uint256 _amount, uint256 _duration ) external; function getRewardFor( address _userAddress, address _policyBook, address _userLeveragePool ) external; function getRewardFor(address _userAddress, address _userLeveragePoolAddress) external; function getReward(address _policyBook, address _userLeveragePool) external; function getReward(address _userLeveragePoolAddress) external; function getShieldTokenAddress(address _policyBook) external view returns (address); function getShieldMiningInfo(address _policyBook) external view returns ( address _rewardsToken, uint256 _decimals, uint256 _firstBlockWithReward, uint256 _lastBlockWithReward, uint256 _lastUpdateBlock, uint256 _nearestLastBlocksWithReward, uint256 _rewardTokensLocked, uint256 _rewardPerTokenStored, uint256 _rewardPerBlock, uint256 _tokenPerDay, uint256 _totalSupply ); function getDepositList( address _account, uint256 _offset, uint256 _limit ) external view returns (ShieldMiningDeposit[] memory _depositsList); function countUsersDeposits(address _account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IPolicyBook.sol"; import "./ILeveragePortfolio.sol"; interface IPolicyBookFacade { /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external; /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external; function policyBook() external view returns (IPolicyBook); function userLiquidity(address account) external view returns (uint256); /// @notice virtual funds deployed by reinsurance pool function VUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by reinsurance pool function LUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by user leverage pool function LUuserLeveragePool(address userLeveragePool) external view returns (uint256); /// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) function totalLeveragedLiquidity() external view returns (uint256); function userleveragedMPL() external view returns (uint256); function reinsurancePoolMPL() external view returns (uint256); function rebalancingThreshold() external view returns (uint256); function safePricingModel() external view returns (bool); /// @notice policyBookFacade initializer /// @param pbProxy polciybook address upgreadable cotnract. function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 initialDeposit ) external; /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @param _buyer who is buying the coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributorFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _user the one taht add liquidity /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view returns ( uint256, uint256, uint256, address ); /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external; /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external; /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external; /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external; /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external; /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external; function listUserLeveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _userLeveragePools); function countUserLeveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IPolicyBookAdmin { function getUpgrader() external view returns (address); function getImplementationOfPolicyBook(address policyBookAddress) external returns (address); function getImplementationOfPolicyBookFacade(address policyBookFacadeAddress) external returns (address); function getCurrentPolicyBooksImplementation() external view returns (address); function getCurrentPolicyBooksFacadeImplementation() external view returns (address); function getCurrentUserLeverageImplementation() external view returns (address); /// @notice It blacklists or whitelists a PolicyBook. Only whitelisted PolicyBooks can /// receive stakes and funds /// @param policyBookAddress PolicyBook address that will be whitelisted or blacklisted /// @param whitelisted true to whitelist or false to blacklist a PolicyBook function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice Whitelist distributor address. Commission fee is 2-5% of the Premium /// It comes from the Protocol’s fee part /// @dev If commission fee is 5%, so _distributorFee = 5 /// @param _distributor distributor address that will receive funds /// @param _distributorFee distributor fee amount function whitelistDistributor(address _distributor, uint256 _distributorFee) external; /// @notice Removes a distributor address from the distributor whitelist /// @param _distributor distributor address that will be blacklist function blacklistDistributor(address _distributor) external; /// @notice Distributor commission fee is 2-5% of the Premium /// It comes from the Protocol’s fee part /// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5 /// @param _distributor address of the distributor /// @return true if address is a whitelisted distributor function isWhitelistedDistributor(address _distributor) external view returns (bool); /// @notice Distributor commission fee is 2-5% of the Premium /// It comes from the Protocol’s fee part /// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5 /// @param _distributor address of the distributor /// @return distributor fee value. It is distributor commission function distributorFees(address _distributor) external view returns (uint256); /// @notice Used to get a list of whitelisted distributors /// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5 /// @return _distributors a list containing distritubors addresses /// @return _distributorsFees a list containing distritubors fees function listDistributors(uint256 offset, uint256 limit) external view returns (address[] memory _distributors, uint256[] memory _distributorsFees); /// @notice Returns number of whitelisted distributors, access: ANY function countDistributors() external view returns (uint256); /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _userLeverageMPL uint256 value of the user leverage mpl; /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage mpl function setPolicyBookFacadeMPLs( address _facadeAddress, uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL ) external; /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _newRebalancingThreshold uint256 value of the reinsurance leverage mpl function setPolicyBookFacadeRebalancingThreshold( address _facadeAddress, uint256 _newRebalancingThreshold ) external; /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setPolicyBookFacadeSafePricingModel(address _facadeAddress, bool _safePricingModel) external; function setLeveragePortfolioRebalancingThreshold( address _LeveragePoolAddress, uint256 _newRebalancingThreshold ) external; function setLeveragePortfolioProtocolConstant( address _LeveragePoolAddress, uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a_ProtocolConstant, uint256 _max_ProtocolConstant ) external; function setUserLeverageMaxCapacities(address _userLeverageAddress, uint256 _maxCapacities) external; /// @notice setup all pricing model varlues ///@param _riskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is considered risky, % ///@param _minimumCostPercentage MC minimum cost of cover (Premium), %; ///@param _minimumInsuranceCost minimum cost of insurance (Premium) , (10**18) ///@param _lowRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is not considered risky (Premium) ///@param _lowRiskMaxPercentPremiumCost100Utilization MCI not risky ///@param _highRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is considered risky (Premium) ///@param _highRiskMaxPercentPremiumCost100Utilization MCI risky function setupPricingModel( uint256 _riskyAssetThresholdPercentage, uint256 _minimumCostPercentage, uint256 _minimumInsuranceCost, uint256 _lowRiskMaxPercentPremiumCost, uint256 _lowRiskMaxPercentPremiumCost100Utilization, uint256 _highRiskMaxPercentPremiumCost, uint256 _highRiskMaxPercentPremiumCost100Utilization ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; uint256 reinsurancePrice; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BuyPolicyParameters { address buyer; address holder; uint256 epochsNumber; uint256 coverTokens; uint256 distributorFee; address distributor; } function policyHolders(address _holder) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function policyBookFacade() external view returns (IPolicyBookFacade); function setPolicyBookFacade(address _policyBookFacade) external; function EPOCH_DURATION() external view returns (uint256); function stblDecimals() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); // /// @notice return MPL for user leverage pool // function userleveragedMPL() external view returns (uint256); // /// @notice return MPL for reinsurance pool // function reinsurancePoolMPL() external view returns (uint256); // function bmiRewardMultiplier() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price /// @param _epochsNumber is number of epochs to cover /// @param _coverTokens is number of tokens to cover /// @param _buyer address of the user who buy the policy /// @return totalSeconds is number of seconds to cover /// @return totalPrice is the policy price which will pay by the buyer function getPolicyPrice( uint256 _epochsNumber, uint256 _coverTokens, address _buyer ) external view returns ( uint256 totalSeconds, uint256 totalPrice, uint256 pricePercentage ); /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _buyer who is transferring funds /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicy( address _buyer, address _holder, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) external returns (uint256, uint256); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityBuyerAddr address the one that transfer funds /// @param _liquidityHolderAddr address the one that owns liquidity /// @param _liquidityAmount uint256 amount to be added on behalf the sender /// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake function addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) external returns (uint256); function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity(address sender) external returns (uint256); ///@notice for doing defi hard rebalancing, access: policyBookFacade function updateLiquidity(uint256 _newLiquidity) external; function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityRegistry { struct LiquidityInfo { address policyBookAddr; uint256 lockedAmount; uint256 availableAmount; uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin } struct WithdrawalRequestInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableLiquidity; uint256 readyToWithdrawDate; uint256 endWithdrawDate; } struct WithdrawalSetInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableSTBLAmount; } function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external; function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external; function getPolicyBooksArrLength(address _userAddr) external view returns (uint256); function getPolicyBooksArr(address _userAddr) external view returns (address[] memory _resultArr); function getLiquidityInfos( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (LiquidityInfo[] memory _resultArr); function getWithdrawalRequests( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr); function getWithdrawalSet( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr); function registerWithdrawl(address _policyBook, address _users) external; function getAllPendingWithdrawalRequestsAmount() external returns (uint256 _totalWithdrawlAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILeveragePortfolio { enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL} struct LevFundsFactors { uint256 netMPL; uint256 netMPLn; address policyBookAddr; // uint256 poolTotalLiquidity; // uint256 poolUR; // uint256 minUR; } function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. function deployVirtualStableToCoveragePools() external returns (uint256); /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner /// @param threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 threshold) external; /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a_ProtocolConstant uint256 A protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a_ProtocolConstant, uint256 _max_ProtocolConstant ) external; /// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max) /// @param poolUR uint256 utitilization ratio for a coverage pool /// @return uint256 M facotr //function calcM(uint256 poolUR) external returns (uint256); /// @return uint256 the amount of vStable stored in the pool function totalLiquidity() external view returns (uint256); /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount); function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant REBALANCE_DURATION = 1 days; uint256 constant EPOCH_DAYS_AMOUNT = 7;
upserts a withdraw request prevents adding a request if an already pending or ready request is open. _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external override { IPolicyBook.WithdrawalStatus _withdrawlStatus = policyBook.getWithdrawalStatus(msg.sender); require( _withdrawlStatus == IPolicyBook.WithdrawalStatus.NONE || _withdrawlStatus == IPolicyBook.WithdrawalStatus.EXPIRED, "PBf: ongoing withdrawl request" ); policyBook.requestWithdrawal(_tokensToWithdraw, msg.sender); liquidityRegistry.registerWithdrawl(address(policyBook), msg.sender); }
234,811
./partial_match/1/0x74b219d1805460B705f4f01C839a954a530B184D/sources/contracts/splootsNFT.sol
Function that opensea calls to grab the images takes base uri and appends the token id to the end tokens have images stored in ipfs and pinned with individual CIDs in pinata Takes URL, grabs ID, places behind URL, and places it as a JSON for OpenSea
function tokenURI( uint256 tokenID_ ) public view override returns (string memory) { require(_exists(tokenID_), "Token does not exist"); return string( abi.encodePacked( baseTokenUri, Strings.toString(tokenID_), ".json" ) ); }
4,383,227
// 0xRACER is a brand new team-based pot lottery game. // Users are grouped into teams based on the first byte of their address. // Team One: 0x0..., 0x1..., 0x2..., 0x3..., 0x4..., 0x5..., 0x6..., 0x7... // Team Two: 0x8..., 0x9..., 0xa..., 0xb..., 0xc..., 0xd..., 0xe..., 0x0... // DISCLAIMER: This is an experimental game in distributed psychology and distributed technology. // DISCLAIMER: You can, and likely will, lose any ETH you send to this contract. Don't send more than you can afford to lose. Or any at all. // RULES: // 1. The team with the highest buy volume when the clock expires wins the pot. // 2. The pot is divided among the winning team members, proportional to a weighted share of team volume. // 3. Each team has a different share price that increases at a rate of 102% per ETH of buy volume. // 4. Every new buy adds time to the clock at the rate of 1 second/finney. The timer is capped at 24h. // 5. You can also reduce the clock at the rate of 1 second/finney, but this does not count towards your share. The timer can't go below 5 minutes with this method. // 6. Referrals and dividends are distributed by team. 50% of each new buy is proportionally split between that team's members. // 7. New seeded rounds with new teams will begin on a semi-regular basis based on user interest. Each game will use a new contract. // 8. In the unlikely event of a tie, the pot is distributed proportionally as weighted shares of total volume. // 9. The minimum buy starts at 1 finney and increases with share price. No maximum. // 10. There is no maximum buy, but large buys receive proportionally fewer shares. For example: 1 x 100 ETH buy (33,333 shares) vs. 100 x 1 ETH (55,265 shares). // 10. No contracts allowed. // 11. Users can withdraw earned dividends from referrals or pot wins at any time. Shares cannot be sold. // 12. The round will automatically open based on a preset timer. // 13. The contract will be closed no sooner than 100 days after the round ends. Any unclaimed user funds left past this time may be lost. // STRATEGY: // A. This game is designed to support multiple modes of play. // B. Get in early and shill your team to collect divs. // C. Manage risk by playing both sides of the fence. // D. Flex your whale wallet by front running and reducing the timer. // E. Piggy back on big players by making sure you're on the same team. // F. Gain a larger share of divs by supporting the underdog. // G. Buy smaller amounts to maximize your share count. // https://zeroxracer.surge.sh/ // https://discord.gg/6Q7kGpc // by nightman pragma solidity ^0.4.24; contract ZEROxRACER { //VARIABLES AND CONSTANTS //global address public owner; uint256 public devBalance; uint256 public devFeeRate = 4; //4% of pot, not volume; effective dev fee, including premine, is ~2.5-3.5% depending on volume uint256 public precisionFactor = 6; //shares precise to 0.0001% address public addressThreshold = 0x7F00000000000000000000000000000000000000; //0x00-0x7f on Team One; 0x80-0xff on Team Two uint256 public divRate = 50; //50% dividends for each buy, distributed proportionally to weighted team volume //team accounting uint256 public teamOneId = 1; string public teamOnePrefix = "Team 0x1234567"; uint256 public teamOneVolume; uint256 public teamOneShares; uint256 public teamOneDivsTotal; uint256 public teamOneDivsUnclaimed; uint256 public teamOneSharePrice = 1000000000000000; //1 finney starting price; increases 102% per ETH bought uint256 public teamTwoId = 2; string public teamTwoPrefix = "Team 0x89abcdef"; uint256 public teamTwoVolume; uint256 public teamTwoShares; uint256 public teamTwoDivsTotal; uint256 public teamTwoDivsUnclaimed; uint256 public teamTwoSharePrice = 1000000000000000; //1 finney starting price; increases 102% per ETH bought //user accounting address[] public teamOneMembers; mapping (address => bool) public isTeamOneMember; mapping (address => uint256) public userTeamOneStake; mapping (address => uint256) public userTeamOneShares; mapping (address => uint256) private userDivsTeamOneTotal; mapping (address => uint256) private userDivsTeamOneClaimed; mapping (address => uint256) private userDivsTeamOneUnclaimed; mapping (address => uint256) private userDivRateTeamOne; address[] public teamTwoMembers; mapping (address => bool) public isTeamTwoMember; mapping (address => uint256) public userTeamTwoStake; mapping (address => uint256) public userTeamTwoShares; mapping (address => uint256) private userDivsTeamTwoTotal; mapping (address => uint256) private userDivsTeamTwoClaimed; mapping (address => uint256) private userDivsTeamTwoUnclaimed; mapping (address => uint256) private userDivRateTeamTwo; //round accounting uint256 public pot; uint256 public timerStart; uint256 public timerMax; uint256 public roundStartTime; uint256 public roundEndTime; bool public roundOpen = false; bool public roundSetUp = false; bool public roundResolved = false; //CONSTRUCTOR constructor() public { owner = msg.sender; emit contractLaunched(owner); } //MODIFIERS modifier onlyOwner() { require (msg.sender == owner, "you are not the owner"); _; } modifier gameOpen() { require (roundResolved == false); require (roundSetUp == true); require (now < roundEndTime, "it is too late to play"); require (now >= roundStartTime, "it is too early to play"); _; } modifier onlyHumans() { require (msg.sender == tx.origin, "you cannot use a contract"); _; } //EVENTS event potFunded( address _funder, uint256 _amount, string _message ); event teamBuy( address _buyer, uint256 _amount, uint256 _teamID, string _message ); event roundEnded( uint256 _winningTeamId, string _winningTeamString, uint256 _pot, string _message ); event newRoundStarted( uint256 _timeStart, uint256 _timeMax, uint256 _seed, string _message ); event userWithdrew( address _user, uint256 _teamID, uint256 _teamAmount, string _message ); event devWithdrew( address _owner, uint256 _amount, string _message ); event contractClosed( address _owner, uint256 _amount, string _message ); event contractLaunched( address _owner ); //DEV FUNCTIONS //start round function openRound (uint _timerStart, uint _timerMax) public payable onlyOwner() { require (roundOpen == false, "you can only start the game once"); require (roundResolved == false, "you cannot restart a finished game"); require (msg.value == 2 ether, "you must give a decent seed"); //round set up roundSetUp = true; timerStart = _timerStart; timerMax = _timerMax; roundStartTime = 1535504400; //Tuesday, August 28, 2018 9:00:00 PM Eastern Time roundEndTime = 1535504400 + timerStart; pot += msg.value; //the seed is also a sneaky premine //set up correct accounting for 1 ETH buy to each team without calling buy() address devA = 0x5C035Bb4Cb7dacbfeE076A5e61AA39a10da2E956; address devB = 0x84ECB387395a1be65E133c75Ff9e5FCC6F756DB3; teamOneVolume = 1 ether; teamTwoVolume = 1 ether; teamOneMembers.push(devA); teamTwoMembers.push(devB); isTeamOneMember[devA] = true; isTeamOneMember[devB] = true; userTeamOneStake[devA] = 1 ether; userTeamTwoStake[devB] = 1 ether; userTeamOneShares[devA] = 1000; userTeamTwoShares[devB] = 1000; teamOneShares = 1000; teamTwoShares = 1000; emit newRoundStarted(timerStart, timerMax, msg.value, "a new game was just set up"); } //dev withdraw function devWithdraw() public onlyOwner() { require (devBalance > 0, "you must have an available balance"); require(devBalance <= address(this).balance, "you cannot print money"); uint256 shareTemp = devBalance; devBalance = 0; owner.transfer(shareTemp); emit devWithdrew(owner, shareTemp, "the dev just withdrew"); } //close contract //this function allows the dev to collect any wei dust from rounding errors no sooner than 100 days after the game ends //wei dust will be at most (teamOneVolume + teamTwoVolume) / 10 ** precisionFactor (ie, 0.0001% of the total buy volume) //users must withdraw any earned divs before this date, or risk losing them function zeroOut() public onlyOwner() { require (now >= roundEndTime + 100 days, "too early to exit scam"); require (roundResolved == true && roundOpen == false, "the game is not resolved"); emit contractClosed(owner, address(this).balance, "the contract is now closed"); selfdestruct(owner); } //PUBLIC FUNCTIONS function buy() public payable gameOpen() onlyHumans() { //toggle roundOpen on first buy after roundStartTime if (roundOpen == false && now >= roundStartTime && now < roundEndTime) { roundOpen = true; } //establish team affiliation uint256 _teamID; if (checkAddressTeamOne(msg.sender) == true) { _teamID = 1; } else if (checkAddressTeamTwo(msg.sender) == true) { _teamID = 2; } //adjust pot and div balances if (_teamID == 1 && teamOneMembers.length == 0 || _teamID == 2 && teamTwoMembers.length == 0) { //do not distribute divs on first buy from either team. prevents black-holed ether //redundant if openRound() includes a premine pot += msg.value; } else { uint256 divContribution = uint256(SafeMaths.div(SafeMaths.mul(msg.value, divRate), 100)); uint256 potContribution = msg.value - divContribution; pot += potContribution; distributeDivs(divContribution, _teamID); } //adjust time timeAdjustPlus(); //update team and player accounting if (_teamID == 1) { require (msg.value >= teamOneSharePrice, "you must buy at least one Team One share"); if (isTeamOneMember[msg.sender] == false) { isTeamOneMember[msg.sender] = true; teamOneMembers.push(msg.sender); } userTeamOneStake[msg.sender] += msg.value; teamOneVolume += msg.value; //adjust team one share price uint256 shareIncreaseOne = SafeMaths.mul(SafeMaths.div(msg.value, 100000), 2); //increases 102% per ETH spent teamOneSharePrice += shareIncreaseOne; uint256 newSharesOne = SafeMaths.div(msg.value, teamOneSharePrice); userTeamOneShares[msg.sender] += newSharesOne; teamOneShares += newSharesOne; } else if (_teamID == 2) { require (msg.value >= teamTwoSharePrice, "you must buy at least one Team Two share"); if (isTeamTwoMember[msg.sender] == false) { isTeamTwoMember[msg.sender] = true; teamTwoMembers.push(msg.sender); } userTeamTwoStake[msg.sender] += msg.value; teamTwoVolume += msg.value; //adjust team two share price uint256 shareIncreaseTwo = SafeMaths.mul(SafeMaths.div(msg.value, 100000), 2); //increases 102% per ETH spent teamTwoSharePrice += shareIncreaseTwo; uint256 newSharesTwo = SafeMaths.div(msg.value, teamTwoSharePrice); userTeamTwoShares[msg.sender] += newSharesTwo; teamTwoShares += newSharesTwo; } emit teamBuy(msg.sender, msg.value, _teamID, "a new buy just happened"); } function resolveRound() public onlyHumans() { //can be called by anyone if the round has ended require (now > roundEndTime, "you can only call this if time has expired"); require (roundSetUp == true, "you cannot call this before the game starts"); require (roundResolved == false, "you can only call this once"); //resolve round based on current winner if (teamOneVolume > teamTwoVolume) { teamOneWin(); } else if (teamOneVolume < teamTwoVolume) { teamTwoWin(); } else if (teamOneVolume == teamTwoVolume) { tie(); } //ensure this function can only be called once roundResolved = true; roundOpen = false; } function userWithdraw() public onlyHumans() { //user divs calculated on withdraw to prevent runaway gas costs associated with looping balance updates in distributeDivs if (userTeamOneShares[msg.sender] > 0) { //first, calculate total earned user divs as a proportion of their shares vs. team shares //second, determine whether the user has available divs //precise to 0.0001% userDivRateTeamOne[msg.sender] = SafeMaths.div(SafeMaths.div(SafeMaths.mul(userTeamOneShares[msg.sender], 10 ** (precisionFactor + 1)), teamOneShares) + 5, 10); userDivsTeamOneTotal[msg.sender] = uint256(SafeMaths.div(SafeMaths.mul(teamOneDivsTotal, userDivRateTeamOne[msg.sender]), 10 ** precisionFactor)); userDivsTeamOneUnclaimed[msg.sender] = SafeMaths.sub(userDivsTeamOneTotal[msg.sender], userDivsTeamOneClaimed[msg.sender]); if (userDivsTeamOneUnclaimed[msg.sender] > 0) { //sanity check assert(userDivsTeamOneUnclaimed[msg.sender] <= address(this).balance && userDivsTeamOneUnclaimed[msg.sender] <= teamOneDivsUnclaimed); //update user accounting and transfer teamOneDivsUnclaimed -= userDivsTeamOneUnclaimed[msg.sender]; userDivsTeamOneClaimed[msg.sender] = userDivsTeamOneTotal[msg.sender]; uint256 shareTempTeamOne = userDivsTeamOneUnclaimed[msg.sender]; userDivsTeamOneUnclaimed[msg.sender] = 0; msg.sender.transfer(shareTempTeamOne); emit userWithdrew(msg.sender, 1, shareTempTeamOne, "a user just withdrew team one shares"); } } else if (userTeamTwoShares[msg.sender] > 0) { //first, calculate total earned user divs as a proportion of their shares vs. team shares //second, determine whether the user has available divs //precise to 0.0001% userDivRateTeamTwo[msg.sender] = SafeMaths.div(SafeMaths.div(SafeMaths.mul(userTeamTwoShares[msg.sender], 10 ** (precisionFactor + 1)), teamTwoShares) + 5, 10); userDivsTeamTwoTotal[msg.sender] = uint256(SafeMaths.div(SafeMaths.mul(teamTwoDivsTotal, userDivRateTeamTwo[msg.sender]), 10 ** precisionFactor)); userDivsTeamTwoUnclaimed[msg.sender] = SafeMaths.sub(userDivsTeamTwoTotal[msg.sender], userDivsTeamTwoClaimed[msg.sender]); if (userDivsTeamTwoUnclaimed[msg.sender] > 0) { //sanity check assert(userDivsTeamTwoUnclaimed[msg.sender] <= address(this).balance && userDivsTeamTwoUnclaimed[msg.sender] <= teamTwoDivsUnclaimed); //update user accounting and transfer teamTwoDivsUnclaimed -= userDivsTeamTwoUnclaimed[msg.sender]; userDivsTeamTwoClaimed[msg.sender] = userDivsTeamTwoTotal[msg.sender]; uint256 shareTempTeamTwo = userDivsTeamTwoUnclaimed[msg.sender]; userDivsTeamTwoUnclaimed[msg.sender] = 0; msg.sender.transfer(shareTempTeamTwo); emit userWithdrew(msg.sender, 2, shareTempTeamTwo, "a user just withdrew team one shares"); } } } function fundPot() public payable onlyHumans() gameOpen() { //ETH sent with this function is a benevolent gift. It does not count towards user shares or adjust the clock pot += msg.value; emit potFunded(msg.sender, msg.value, "a generous person funded the pot"); } function reduceTime() public payable onlyHumans() gameOpen() { //ETH sent with this function does not count towards user shares timeAdjustNeg(); pot += msg.value; emit potFunded(msg.sender, msg.value, "someone just reduced the clock"); } //VIEW FUNCTIONS function calcUserDivsTotal(address _user) public view returns(uint256 _divs) { //calculated locally to avoid unnecessary state change if (userTeamOneShares[_user] > 0) { uint256 userDivRateTeamOneView = SafeMaths.div(SafeMaths.div(SafeMaths.mul(userTeamOneShares[_user], 10 ** (precisionFactor + 1)), teamOneShares) + 5, 10); uint256 userDivsTeamOneTotalView = uint256(SafeMaths.div(SafeMaths.mul(teamOneDivsTotal, userDivRateTeamOneView), 10 ** precisionFactor)); } else if (userTeamTwoShares[_user] > 0) { uint256 userDivRateTeamTwoView = SafeMaths.div(SafeMaths.div(SafeMaths.mul(userTeamTwoShares[_user], 10 ** (precisionFactor + 1)), teamTwoShares) + 5, 10); uint256 userDivsTeamTwoTotalView = uint256(SafeMaths.div(SafeMaths.mul(teamTwoDivsTotal, userDivRateTeamTwoView), 10 ** precisionFactor)); } uint256 userDivsTotal = userDivsTeamOneTotalView + userDivsTeamTwoTotalView; return userDivsTotal; } function calcUserDivsAvailable(address _user) public view returns(uint256 _divs) { //calculated locally to avoid unnecessary state change if (userTeamOneShares[_user] > 0) { uint256 userDivRateTeamOneView = SafeMaths.div(SafeMaths.div(SafeMaths.mul(userTeamOneShares[_user], 10 ** (precisionFactor + 1)), teamOneShares) + 5, 10); uint256 userDivsTeamOneTotalView = uint256(SafeMaths.div(SafeMaths.mul(teamOneDivsTotal, userDivRateTeamOneView), 10 ** precisionFactor)); uint256 userDivsTeamOneUnclaimedView = SafeMaths.sub(userDivsTeamOneTotalView, userDivsTeamOneClaimed[_user]); } else if (userTeamTwoShares[_user] > 0) { uint256 userDivRateTeamTwoView = SafeMaths.div(SafeMaths.div(SafeMaths.mul(userTeamTwoShares[_user], 10 ** (precisionFactor + 1)), teamTwoShares) + 5, 10); uint256 userDivsTeamTwoTotalView = uint256(SafeMaths.div(SafeMaths.mul(teamTwoDivsTotal, userDivRateTeamTwoView), 10 ** precisionFactor)); uint256 userDivsTeamTwoUnclaimedView = SafeMaths.sub(userDivsTeamTwoTotalView, userDivsTeamTwoClaimed[_user]); } uint256 userDivsUnclaimed = userDivsTeamOneUnclaimedView + userDivsTeamTwoUnclaimedView; return userDivsUnclaimed; } function currentRoundInfo() public view returns( uint256 _pot, uint256 _teamOneVolume, uint256 _teamTwoVolume, uint256 _teamOnePlayerCount, uint256 _teamTwoPlayerCount, uint256 _totalPlayerCount, uint256 _timerStart, uint256 _timerMax, uint256 _roundStartTime, uint256 _roundEndTime, uint256 _timeLeft, string _currentWinner ) { return ( pot, teamOneVolume, teamTwoVolume, teamOneTotalPlayers(), teamTwoTotalPlayers(), totalPlayers(), timerStart, timerMax, roundStartTime, roundEndTime, getTimeLeft(), currentWinner() ); } function getTimeLeft() public view returns(uint256 _timeLeftSeconds) { //game over: display zero if (now >= roundEndTime) { return 0; //game not yet started: display countdown until roundStartTime } else if (roundOpen == false && roundResolved == false && roundSetUp == false) { return roundStartTime - now; //game in progress: display time left } else { return roundEndTime - now; } } function teamOneTotalPlayers() public view returns(uint256 _teamOnePlayerCount) { return teamOneMembers.length; } function teamTwoTotalPlayers() public view returns(uint256 _teamTwoPlayerCount) { return teamTwoMembers.length; } function totalPlayers() public view returns(uint256 _totalPlayerCount) { return teamOneMembers.length + teamTwoMembers.length; } function adjustedPotBalance() public view returns(uint256 _adjustedPotBalance) { uint256 devFee = uint256(SafeMaths.div(SafeMaths.mul(pot, devFeeRate), 100)); return pot - devFee; } function contractBalance() public view returns(uint256 _contractBalance) { return address(this).balance; } function currentTime() public view returns(uint256 _time) { return now; } function currentWinner() public view returns(string _winner) { if (teamOneVolume > teamTwoVolume) { return teamOnePrefix; } else if (teamOneVolume < teamTwoVolume) { return teamTwoPrefix; } else if (teamOneVolume == teamTwoVolume) { return "a tie? wtf"; } } //INTERNAL FUNCTIONS //time adjustments function timeAdjustPlus() internal { if (msg.value >= 1 finney) { uint256 timeFactor = 1000000000000000; //one finney in wei uint256 timeShares = uint256(SafeMaths.div(msg.value, timeFactor)); if (timeShares + roundEndTime > now + timerMax) { roundEndTime = now + timerMax; } else { roundEndTime += timeShares; //add one second per finney } } } function timeAdjustNeg() internal { if (msg.value >= 1 finney) { uint256 timeFactor = 1000000000000000; //one finney in wei uint256 timeShares = uint256(SafeMaths.div(msg.value, timeFactor)); // prevents extreme edge case underflow if someone sends more than 1.5 million ETH require (timeShares < roundEndTime, "you sent an absurd amount! relax vitalik"); if (roundEndTime - timeShares < now + 5 minutes) { roundEndTime = now + 5 minutes; //you can't win by buying up the clock, but you can come close } else { roundEndTime -= timeShares; //subtract one second per finney } } } //divs function distributeDivs(uint256 _divContribution, uint256 _teamID) internal { if (_teamID == 1) { teamOneDivsTotal += _divContribution; teamOneDivsUnclaimed += _divContribution; } else if (_teamID == 2) { teamTwoDivsTotal += _divContribution; teamTwoDivsUnclaimed += _divContribution; } } //round payouts function teamOneWin() internal { uint256 devShare = uint256(SafeMaths.div(SafeMaths.mul(pot, devFeeRate), 100)); devBalance += devShare; uint256 potAdjusted = pot - devShare; teamOneDivsTotal += potAdjusted; teamOneDivsUnclaimed += potAdjusted; emit roundEnded(1, teamOnePrefix, potAdjusted, "team one won!"); } function teamTwoWin() internal { uint256 devShare = uint256(SafeMaths.div(SafeMaths.mul(pot, devFeeRate), 100)); devBalance += devShare; uint256 potAdjusted = pot - devShare; teamTwoDivsTotal += potAdjusted; teamTwoDivsUnclaimed += potAdjusted; emit roundEnded(2, teamTwoPrefix, potAdjusted, "team two won!"); } function tie() internal { //very unlikely this will happen, but just in case uint256 devShare = uint256(SafeMaths.div(SafeMaths.mul(pot, devFeeRate), 100)); devBalance += devShare; uint256 potAdjusted = pot - devShare; teamOneDivsTotal += SafeMaths.div(potAdjusted, 2); teamOneDivsUnclaimed += SafeMaths.div(potAdjusted, 2); teamTwoDivsTotal += SafeMaths.div(potAdjusted, 2); teamTwoDivsUnclaimed += SafeMaths.div(potAdjusted, 2); emit roundEnded(0, "Tied", potAdjusted, "a tie?! wtf"); } //convert and address to bytes format function toBytes(address a) internal pure returns (bytes b) { assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } return b; } //take the first byte of a bytes argument and return bytes1 function toBytes1(bytes data) internal pure returns (bytes1) { uint val; for (uint i = 0; i < 1; i++) { val *= 256; if (i < data.length) val |= uint8(data[i]); } return bytes1(val); } //combine the above function function addressToBytes1(address input) internal pure returns(bytes1) { bytes1 output = toBytes1(toBytes(input)); return output; } //address checks function checkAddressTeamOne(address _input) internal view returns(bool) { if (addressToBytes1(_input) <= addressToBytes1(addressThreshold)) { return true; } else { return false; } } function checkAddressTeamTwo(address _input) internal view returns(bool) { if (addressToBytes1(_input) > addressToBytes1(addressThreshold)) { return true; } else { return false; } } } //LIBRARIES library SafeMaths { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
can be called by anyone if the round has endedresolve round based on current winner
function resolveRound() public onlyHumans() { require (now > roundEndTime, "you can only call this if time has expired"); require (roundSetUp == true, "you cannot call this before the game starts"); require (roundResolved == false, "you can only call this once"); if (teamOneVolume > teamTwoVolume) { teamOneWin(); teamTwoWin(); tie(); } roundOpen = false; }
12,681,011
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardEvents.sol /// @title Witnet Request Board emitting events interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardEvents { /// Emitted when a Witnet Data Request is posted to the WRB. event PostedRequest(uint256 queryId, address from); /// Emitted when a Witnet-solved result is reported to the WRB. event PostedResult(uint256 queryId, address from); /// Emitted when all data related to given query is deleted from the WRB. event DeletedQuery(uint256 queryId, address from); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardReporter.sol /// @title The Witnet Request Board Reporter interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardReporter { /// Reports the Witnet-provided result to a previously posted request. /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved. /// @dev Fails if: /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique identifier of the data request. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, bytes32 _drTxHash, bytes calldata _result) external; /// Reports the Witnet-provided result to a previously posted request. /// @dev Fails if: /// @dev - called from unauthorized address; /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique query identifier /// @param _timestamp The timestamp of the solving tally transaction in Witnet. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _result) external; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequest.sol /// @title The Witnet Data Request basic interface. /// @author The Witnet Foundation. interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); } // File: node_modules\witnet-solidity-bridge\contracts\libs\Witnet.sol library Witnet { /// @notice Witnet function that computes the hash of a CBOR-encoded Data Request. /// @param _bytecode CBOR-encoded RADON. function hash(bytes memory _bytecode) internal pure returns (bytes32) { return sha256(_bytecode); } /// Struct containing both request and response data related to every query posted to the Witnet Request Board struct Query { Request request; Response response; } /// Possible status of a Witnet query. enum QueryStatus { Unknown, Posted, Reported, Deleted } /// Data kept in EVM-storage for every Request posted to the Witnet Request Board. struct Request { IWitnetRequest addr; // The contract containing the Data Request which execution has been requested. address requester; // Address from which the request was posted. bytes32 hash; // Hash of the Data Request whose execution has been requested. uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx. uint256 reward; // Escrowed reward to be paid to the DR resolver. } /// Data kept in EVM-storage containing Witnet-provided response metadata and result. struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. } /// Data struct containing the Witnet-provided result to a Data Request. struct Result { bool success; // Flag stating whether the request could get solved successfully, or not. CBOR value; // Resulting value, in CBOR-serialized bytes. } /// Data struct following the RFC-7049 standard: Concise Binary Object Representation. struct CBOR { Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /// Iterable bytes buffer. struct Buffer { bytes data; uint32 cursor; } /// Witnet error codes table. enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid Data Request. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardRequestor.sol /// @title Witnet Requestor Interface /// @notice It defines how to interact with the Witnet Request Board in order to: /// - request the execution of Witnet Radon scripts (data request); /// - upgrade the resolution reward of any previously posted request, in case gas price raises in mainnet; /// - read the result of any previously posted request, eventually reported by the Witnet DON. /// - remove from storage all data related to past and solved data requests, and results. /// @author The Witnet Foundation. interface IWitnetRequestBoardRequestor { /// Retrieves a copy of all Witnet-provided data related to a previously posted request, removing the whole query from the WRB storage. /// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to /// @dev the one that actually posted the given request. /// @param _queryId The unique query identifier. function deleteQuery(uint256 _queryId) external returns (Witnet.Response memory); /// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON. /// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided /// result to this request. /// @dev Fails if: /// @dev - provided reward is too low. /// @dev - provided script is zero address. /// @dev - provided script bytecode is empty. /// @param _addr The address of the IWitnetRequest contract that can provide the actual Data Request bytecode. /// @return _queryId An unique query identifier. function postRequest(IWitnetRequest _addr) external payable returns (uint256 _queryId); /// Increments the reward of a previously posted request by adding the transaction value to it. /// @dev Updates request `gasPrice` in case this method is called with a higher /// @dev gas price value than the one used in previous calls to `postRequest` or /// @dev `upgradeReward`. /// @dev Fails if the `_queryId` is not in 'Posted' status. /// @dev Fails also in case the request `gasPrice` is increased, and the new /// @dev reward value gets below new recalculated threshold. /// @param _queryId The unique query identifier. function upgradeReward(uint256 _queryId) external payable; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardView.sol /// @title Witnet Request Board info interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardView { /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) external view returns (uint256); /// Returns next query id to be generated by the Witnet Request Board. function getNextQueryId() external view returns (uint256); /// Gets the whole Query data contents, if any, no matter its current status. function getQueryData(uint256 _queryId) external view returns (Witnet.Query memory); /// Gets current status of given query. function getQueryStatus(uint256 _queryId) external view returns (Witnet.QueryStatus); /// Retrieves the whole `Witnet.Request` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequest(uint256 _queryId) external view returns (Witnet.Request memory); /// Retrieves the serialized bytecode of a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestBytecode(uint256 _queryId) external view returns (bytes memory); /// Retrieves the gas price that any assigned reporter will have to pay when reporting result /// to the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestGasPrice(uint256 _queryId) external view returns (uint256); /// Retrieves the reward currently set for the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestReward(uint256 _queryId) external view returns (uint256); /// Retrieves the whole `Witnet.Response` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponse(uint256 _queryId) external view returns (Witnet.Response memory); /// Retrieves the hash of the Witnet transaction hash that actually solved the referred query. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseDrTxHash(uint256 _queryId) external view returns (bytes32); /// Retrieves the address that reported the result to a previously-posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseReporter(uint256 _queryId) external view returns (address); /// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseResult(uint256 _queryId) external view returns (Witnet.Result memory); /// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseTimestamp(uint256 _queryId) external view returns (uint256); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestParser.sol /// @title The Witnet interface for decoding Witnet-provided request to Data Requests. /// This interface exposes functions to check for the success/failure of /// a Witnet-provided result, as well as to parse and convert result into /// Solidity types suitable to the application level. /// @author The Witnet Foundation. interface IWitnetRequestParser { /// Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes memory _cborBytes) external pure returns (Witnet.Result memory); /// Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure returns (Witnet.Result memory); /// Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool); /// Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool); /// Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns (bytes memory); /// Decode a bytes value from a Witnet.Result as a `bytes32` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes32` decoded from the Witnet.Result. function asBytes32(Witnet.Result memory _result) external pure returns (bytes32); /// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes); /// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes, string memory); /// Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) external pure returns(uint64[] memory); /// Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool); /// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32); /// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory); /// Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128); /// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory); /// Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns (string memory); /// Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory); /// Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64); /// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory); } // File: node_modules\witnet-solidity-bridge\contracts\WitnetRequestBoard.sol /// @title Witnet Request Board functionality base contract. /// @author The Witnet Foundation. abstract contract WitnetRequestBoard is IWitnetRequestBoardEvents, IWitnetRequestBoardReporter, IWitnetRequestBoardRequestor, IWitnetRequestBoardView, IWitnetRequestParser { receive() external payable { revert("WitnetRequestBoard: no transfers accepted"); } } // File: witnet-solidity-bridge\contracts\UsingWitnet.sol /// @title The UsingWitnet contract /// @dev Witnet-aware contracts can inherit from this contract in order to interact with Witnet. /// @author The Witnet Foundation. abstract contract UsingWitnet { WitnetRequestBoard public immutable witnet; /// Include an address to specify the WitnetRequestBoard entry point address. /// @param _wrb The WitnetRequestBoard entry point address. constructor(WitnetRequestBoard _wrb) { require(address(_wrb) != address(0), "UsingWitnet: zero address"); witnet = _wrb; } /// Provides a convenient way for client contracts extending this to block the execution of the main logic of the /// contract until a particular request has been successfully solved and reported by Witnet. modifier witnetRequestSolved(uint256 _id) { require( _witnetCheckResultAvailability(_id), "UsingWitnet: request not solved" ); _; } /// Check if a data request has been solved and reported by Witnet. /// @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. /// parties) before this method returns `true`. /// @param _id The unique identifier of a previously posted data request. /// @return A boolean telling if the request has been already resolved or not. Returns `false` also, if the result was deleted. function _witnetCheckResultAvailability(uint256 _id) internal view virtual returns (bool) { return witnet.getQueryStatus(_id) == Witnet.QueryStatus.Reported; } /// Estimate the reward amount. /// @param _gasPrice The gas price for which we want to retrieve the estimation. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward(uint256 _gasPrice) internal view virtual returns (uint256) { return witnet.estimateReward(_gasPrice); } /// Estimates the reward amount, considering current transaction gas price. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward() internal view virtual returns (uint256) { return witnet.estimateReward(tx.gasprice); } /// Send a new request to the Witnet network with transaction value as a reward. /// @param _request An instance of `IWitnetRequest` contract. /// @return _id Sequential identifier for the request included in the WitnetRequestBoard. /// @return _reward Current reward amount escrowed by the WRB until a result gets reported. function _witnetPostRequest(IWitnetRequest _request) internal virtual returns (uint256 _id, uint256 _reward) { _reward = _witnetEstimateReward(); _id = witnet.postRequest{value: _reward}(_request); } /// Upgrade the reward for a previously posted request. /// @dev Call to `upgradeReward` function in the WitnetRequestBoard contract. /// @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. /// @return Amount in which the reward has been increased. function _witnetUpgradeReward(uint256 _id) internal virtual returns (uint256) { uint256 _currentReward = witnet.readRequestReward(_id); uint256 _newReward = _witnetEstimateReward(); uint256 _fundsToAdd = 0; if (_newReward > _currentReward) { _fundsToAdd = (_newReward - _currentReward); } witnet.upgradeReward{value: _fundsToAdd}(_id); // Let Request.gasPrice be updated return _fundsToAdd; } /// Read the Witnet-provided result to a previously posted request. /// @param _id The unique identifier of a request that was posted to Witnet. /// @return The result of the request as an instance of `Witnet.Result`. function _witnetReadResult(uint256 _id) internal view virtual returns (Witnet.Result memory) { return witnet.readResponseResult(_id); } /// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage. /// @param _id The unique identifier of a previously posted request. /// @return The Witnet-provided result to the request. function _witnetDeleteQuery(uint256 _id) internal virtual returns (Witnet.Response memory) { return witnet.deleteQuery(_id); } } // File: node_modules\witnet-solidity-bridge\contracts\requests\WitnetRequestBase.sol abstract contract WitnetRequestBase is IWitnetRequest { /// Contains a well-formed Witnet Data Request, encoded using Protocol Buffers. bytes public override bytecode; /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. bytes32 public override hash; } // File: witnet-solidity-bridge\contracts\requests\WitnetRequest.sol contract WitnetRequest is WitnetRequestBase { using Witnet for bytes; constructor(bytes memory _bytecode) { bytecode = _bytecode; hash = _bytecode.hash(); } } // File: ado-contracts\contracts\interfaces\IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/adoracles/EIPs/blob/erc-2362/EIPS/eip-2362.md */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetPriceRouter.sol /// @title The Witnet Price Router basic interface. /// @dev Guides implementation of price feeds aggregation contracts. /// @author The Witnet Foundation. abstract contract IWitnetPriceRouter is IERC2362 { /// Emitted everytime a currency pair is attached to a new price feed contract /// @dev See https://github.com/adoracles/ADOIPs/blob/main/adoip-0010.md /// @dev to learn how these ids are created. event CurrencyPairSet(bytes32 indexed erc2362ID, IERC165 pricefeed); /// Helper pure function: returns hash of the provided ERC2362-compliant currency pair caption (aka ID). function currencyPairId(string memory) external pure virtual returns (bytes32); /// Returns the ERC-165-compliant price feed contract currently serving /// updates on the given currency pair. function getPriceFeed(bytes32 _erc2362id) external view virtual returns (IERC165); /// Returns human-readable ERC2362-based caption of the currency pair being /// served by the given price feed contract address. /// @dev Should fail if the given price feed contract address is not currently /// @dev registered in the router. function getPriceFeedCaption(IERC165) external view virtual returns (string memory); /// Returns human-readable caption of the ERC2362-based currency pair identifier, if known. function lookupERC2362ID(bytes32 _erc2362id) external view virtual returns (string memory); /// Register a price feed contract that will serve updates for the given currency pair. /// @dev Setting zero address to a currency pair implies that it will not be served any longer. /// @dev Otherwise, should fail if the price feed contract does not support the `IWitnetPriceFeed` interface, /// @dev or if given price feed is already serving another currency pair (within this WitnetPriceRouter instance). function setPriceFeed( IERC165 _pricefeed, uint256 _decimals, string calldata _base, string calldata _quote ) external virtual; /// Returns list of known currency pairs IDs. function supportedCurrencyPairs() external view virtual returns (bytes32[] memory); /// Returns `true` if given pair is currently being served by a compliant price feed contract. function supportsCurrencyPair(bytes32 _erc2362id) external view virtual returns (bool); /// Returns `true` if given price feed contract is currently serving updates to any known currency pair. function supportsPriceFeed(IERC165 _priceFeed) external view virtual returns (bool); } // File: node_modules\@openzeppelin\contracts\utils\Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetPriceFeed.sol /// @title The Witnet Price Feed basic interface. /// @dev Guides implementation of active price feed polling contracts. /// @author The Witnet Foundation. interface IWitnetPriceFeed { /// Signals that a new price update request is being posted to the Witnet Request Board event PriceFeeding(address indexed from, uint256 queryId, uint256 extraFee); /// Estimates minimum fee amount in native currency to be paid when /// requesting a new price update. /// @dev Actual fee depends on the gas price of the `requestUpdate()` transaction. /// @param _gasPrice Gas price expected to be paid when calling `requestUpdate()` function estimateUpdateFee(uint256 _gasPrice) external view returns (uint256); /// Returns result of the last valid price update request successfully solved by the Witnet oracle. function lastPrice() external view returns (int256); /// Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle. function lastTimestamp() external view returns (uint256); /// Returns tuple containing last valid price and timestamp, as well as status code of latest update /// request that got posted to the Witnet Request Board. /// @return _lastPrice Last valid price reported back from the Witnet oracle. /// @return _lastTimestamp EVM-timestamp of the last valid price. /// @return _lastDrTxHash Hash of the Witnet Data Request that solved the last valid price. /// @return _latestUpdateStatus Status code of the latest update request. function lastValue() external view returns ( int _lastPrice, uint _lastTimestamp, bytes32 _lastDrTxHash, uint _latestUpdateStatus ); /// Returns identifier of the latest update request posted to the Witnet Request Board. function latestQueryId() external view returns (uint256); /// Returns hash of the Witnet Data Request that solved the latest update request. /// @dev Returning 0 while the latest update request remains unsolved. function latestUpdateDrTxHash() external view returns (bytes32); /// Returns error message of latest update request posted to the Witnet Request Board. /// @dev Returning empty string if the latest update request remains unsolved, or /// @dev if it was succesfully solved with no errors. function latestUpdateErrorMessage() external view returns (string memory); /// Returns status code of latest update request posted to the Witnet Request Board: /// @dev Status codes: /// @dev - 200: update request was succesfully solved with no errors /// @dev - 400: update request was solved with errors /// @dev - 404: update request was not solved yet function latestUpdateStatus() external view returns (uint256); /// Returns `true` if latest update request posted to the Witnet Request Board /// has not been solved yet by the Witnet oracle. function pendingUpdate() external view returns (bool); /// Posts a new price update request to the Witnet Request Board. Requires payment of a fee /// that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`. /// @dev If previous update request was not solved yet, calling this method again allows /// @dev upgrading the update fee if called with a higher `tx.gasprice` value. function requestUpdate() external payable; /// Tells whether this contract implements the interface defined by `interfaceId`. /// @dev See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] /// @dev to learn more about how these ids are created. function supportsInterface(bytes4) external view returns (bool); } // File: @openzeppelin\contracts\utils\Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: witnet-solidity-bridge\contracts\examples\WitnetPriceRouter.sol contract WitnetPriceRouter is IWitnetPriceRouter, Ownable { using Strings for uint256; struct Pair { IERC165 pricefeed; uint256 decimals; string base; string quote; } mapping (bytes32 => Pair) internal __pairs; mapping (address => bytes32) internal __pricefeedId_; bytes32[] internal __supportedCurrencyPairs; // ======================================================================== // --- Implementation of 'IERC2362' --------------------------------------- /// Returns last valid price value and timestamp, as well as status of /// the latest update request that got posted to the Witnet Request Board. /// @dev Fails if the given currency pair is not currently supported. /// @param _erc2362id Price pair identifier as specified in https://github.com/adoracles/ADOIPs/blob/main/adoip-0010.md /// @return _lastPrice Last valid price reported back from the Witnet oracle. /// @return _lastTimestamp EVM-timestamp of the last valid price. /// @return _latestUpdateStatus Status code of latest update request that got posted to the Witnet Request Board: /// - 200: latest update request was succesfully solved with no errors /// - 400: latest update request was solved with errors /// - 404: latest update request is still pending to be solved function valueFor(bytes32 _erc2362id) external view virtual override returns ( int256 _lastPrice, uint256 _lastTimestamp, uint256 _latestUpdateStatus ) { IWitnetPriceFeed _pricefeed = IWitnetPriceFeed(address(getPriceFeed(_erc2362id))); require(address(_pricefeed) != address(0), "WitnetPriceRouter: unsupported currency pair"); (_lastPrice, _lastTimestamp,, _latestUpdateStatus) = _pricefeed.lastValue(); } // ======================================================================== // --- Implementation of 'IWitnetPriceRouter' --------------------------- /// Helper pure function: returns hash of the provided ERC2362-compliant currency pair caption (aka ID). function currencyPairId(string memory _caption) public pure virtual override returns (bytes32) { return keccak256(bytes(_caption)); } /// Returns the ERC-165-compliant price feed contract currently serving /// updates on the given currency pair. function getPriceFeed(bytes32 _erc2362id) public view virtual override returns (IERC165) { return __pairs[_erc2362id].pricefeed; } /// Returns human-readable ERC2362-based caption of the currency pair being /// served by the given price feed contract address. /// @dev Fails if the given price feed contract address is not currently /// @dev registered in the router. function getPriceFeedCaption(IERC165 _pricefeed) public view virtual override returns (string memory) { require(supportsPriceFeed(_pricefeed), "WitnetPriceRouter: unknown"); return lookupERC2362ID(__pricefeedId_[address(_pricefeed)]); } /// Returns human-readable caption of the ERC2362-based currency pair identifier, if known. function lookupERC2362ID(bytes32 _erc2362id) public view virtual override returns (string memory _caption) { Pair storage _pair = __pairs[_erc2362id]; if ( bytes(_pair.base).length > 0 && bytes(_pair.quote).length > 0 ) { _caption = string(abi.encodePacked( "Price-", _pair.base, "/", _pair.quote, "-", _pair.decimals.toString() )); } } /// Register a price feed contract that will serve updates for the given currency pair. /// @dev Setting zero address to a currency pair implies that it will not be served any longer. /// @dev Otherwise, fails if the price feed contract does not support the `IWitnetPriceFeed` interface, /// @dev or if given price feed is already serving another currency pair (within this WitnetPriceRouter instance). function setPriceFeed( IERC165 _pricefeed, uint256 _decimals, string calldata _base, string calldata _quote ) public virtual override onlyOwner { if (address(_pricefeed) != address(0)) { require( _pricefeed.supportsInterface(type(IWitnetPriceFeed).interfaceId), "WitnetPriceRouter: feed contract is not compliant with IWitnetPriceFeed" ); require( __pricefeedId_[address(_pricefeed)] == bytes32(0), "WitnetPriceRouter: already serving a currency pair" ); } bytes memory _caption = abi.encodePacked( "Price-", bytes(_base), "/", bytes(_quote), "-", _decimals.toString() ); bytes32 _erc2362id = keccak256(_caption); Pair storage _record = __pairs[_erc2362id]; address _currentPriceFeed = address(_record.pricefeed); if (bytes(_record.base).length == 0) { _record.base = _base; _record.quote = _quote; _record.decimals = _decimals; __supportedCurrencyPairs.push(_erc2362id); } else if (_currentPriceFeed != address(0)) { __pricefeedId_[_currentPriceFeed] = bytes32(0); } if (address(_pricefeed) != _currentPriceFeed) { __pricefeedId_[address(_pricefeed)] = _erc2362id; } _record.pricefeed = _pricefeed; emit CurrencyPairSet(_erc2362id, _pricefeed); } /// Returns list of known currency pairs IDs. function supportedCurrencyPairs() external view virtual override returns (bytes32[] memory) { return __supportedCurrencyPairs; } /// Returns `true` if given pair is currently being served by a compliant price feed contract. function supportsCurrencyPair(bytes32 _erc2362id) public view virtual override returns (bool) { return address(__pairs[_erc2362id].pricefeed) != address(0); } /// Returns `true` if given price feed contract is currently serving updates to any known currency pair. function supportsPriceFeed(IERC165 _pricefeed) public view virtual override returns (bool) { return __pairs[__pricefeedId_[address(_pricefeed)]].pricefeed == _pricefeed; } } // File: contracts\WitnetPriceFeed.sol // Your contract needs to inherit from UsingWitnet contract WitnetPriceFeed is IWitnetPriceFeed, UsingWitnet, WitnetRequest { using Witnet for bytes; /// Stores the ID of the last price update posted to the Witnet Request Board. uint256 public override latestQueryId; /// Stores the ID of the last price update succesfully solved by the WRB. uint256 internal __lastValidQueryId; /// Constructor. /// @param _witnetRequestBoard WitnetRequestBoard entrypoint address. /// @param _witnetRequestBytecode Raw bytecode of Witnet Data Request to be used on every update request. constructor ( WitnetRequestBoard _witnetRequestBoard, bytes memory _witnetRequestBytecode ) UsingWitnet(_witnetRequestBoard) WitnetRequest(_witnetRequestBytecode) {} /// Estimates minimum fee amount in native currency to be paid when /// requesting a new price update. /// @dev Actual fee depends on the gas price of the `requestUpdate()` transaction. /// @param _gasPrice Gas price expected to be paid when calling `requestUpdate()` function estimateUpdateFee(uint256 _gasPrice) external view virtual override returns (uint256) { return witnet.estimateReward(_gasPrice); } /// Returns result of the last valid price update request successfully solved by the Witnet oracle. function lastPrice() public view virtual override returns (int256 _lastPrice) { Witnet.Result memory _result; uint _latestQueryId = latestQueryId; if ( _latestQueryId > 0 && _witnetCheckResultAvailability(_latestQueryId) ) { _result = witnet.readResponseResult(_latestQueryId); if (_result.success) { return int256(int64(witnet.asUint64(_result))); } } if (__lastValidQueryId > 0) { _result = witnet.readResponseResult(__lastValidQueryId); return int256(int64(witnet.asUint64(_result))); } } /// Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle. function lastTimestamp() public view virtual override returns (uint256 _lastTimestamp) { Witnet.Result memory _result; Witnet.Response memory _response; uint _latestQueryId = latestQueryId; if ( _latestQueryId > 0 && _witnetCheckResultAvailability(_latestQueryId) ) { _response = witnet.readResponse(_latestQueryId); _result = witnet.resultFromCborBytes(_response.cborBytes); if (_result.success) { return _response.timestamp; } } if (__lastValidQueryId > 0) { _response = witnet.readResponse(__lastValidQueryId); return _response.timestamp; } } /// Returns tuple containing last valid price and timestamp, as well as status code of latest update /// request that got posted to the Witnet Request Board. /// @return _lastPrice Last valid price reported back from the Witnet oracle. /// @return _lastTimestamp EVM-timestamp of the last valid price. /// @return _lastDrTxHash Hash of the Witnet Data Request that solved the last valid price. /// @return _latestUpdateStatus Status code of the latest update request. function lastValue() external view virtual override returns ( int _lastPrice, uint _lastTimestamp, bytes32 _lastDrTxHash, uint _latestUpdateStatus ) { uint _latestQueryId = latestQueryId; if (_latestQueryId > 0) { bool _completed = _witnetCheckResultAvailability(_latestQueryId); if (_completed) { Witnet.Response memory _latestResponse = witnet.readResponse(_latestQueryId); Witnet.Result memory _latestResult = witnet.resultFromCborBytes(_latestResponse.cborBytes); if (_latestResult.success) { return ( int256(int64(witnet.asUint64(_latestResult))), _latestResponse.timestamp, _latestResponse.drTxHash, 200 ); } } if (__lastValidQueryId > 0) { Witnet.Response memory _lastValidResponse = witnet.readResponse(__lastValidQueryId); Witnet.Result memory _lastValidResult = witnet.resultFromCborBytes(_lastValidResponse.cborBytes); return ( int256(int64(witnet.asUint64(_lastValidResult))), _lastValidResponse.timestamp, _lastValidResponse.drTxHash, _completed ? 400 : 404 ); } } return (0, 0, 0, 404); } /// Returns identifier of the latest update request posted to the Witnet Request Board. /// @dev Returning 0 while the latest update request remains unsolved. function latestUpdateDrTxHash() external view virtual override returns (bytes32) { uint256 _latestQueryId = latestQueryId; if (_latestQueryId > 0) { if (_witnetCheckResultAvailability(_latestQueryId)) { return witnet.readResponseDrTxHash(_latestQueryId); } } return bytes32(0); } /// Returns error message of latest update request posted to the Witnet Request Board. /// @dev Returning empty string if the latest update request remains unsolved, or /// @dev if it was succesfully solved with no errors. function latestUpdateErrorMessage() external view virtual override returns (string memory _errorMessage) { uint256 _latestQueryId = latestQueryId; if (_latestQueryId > 0) { if (_witnetCheckResultAvailability(_latestQueryId)) { Witnet.Result memory _latestResult = witnet.readResponseResult(_latestQueryId); if (_latestResult.success == false) { (, _errorMessage) = witnet.asErrorMessage(_latestResult); } } } } /// Returns status code of latest update request posted to the Witnet Request Board: /// @dev Status codes: /// @dev - 200: update request was succesfully solved with no errors /// @dev - 400: update request was solved with errors /// @dev - 404: update request was not solved yet function latestUpdateStatus() public view virtual override returns (uint256) { uint _latestQueryId = latestQueryId; if (_latestQueryId > 0) { if (_witnetCheckResultAvailability(_latestQueryId)) { Witnet.Result memory _result = witnet.readResponseResult(_latestQueryId); return ( _result.success ? 200 // OK : 400 // Bad result ); } else { return 404; // not yet solved; } } return 200; } /// Returns `true` if latest update request posted to the Witnet Request Board /// has not been solved yet by the Witnet oracle. function pendingUpdate() public view virtual override returns (bool) { return ( latestQueryId != 0 && !_witnetCheckResultAvailability(latestQueryId) ); } /// Posts a new price update request to the Witnet Request Board. Requires payment of a fee /// that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`. /// @dev If previous update request was not solved yet, calling this method again allows /// @dev upgrading the update fee if called with a higher `tx.gasprice` value. function requestUpdate() public payable virtual override { uint _usedFunds; uint _latestQueryId = latestQueryId; uint _latestUpdateStatus = latestUpdateStatus(); if (_latestUpdateStatus == 404) { // latest update is still pending, so just raise upgrade reward, // accordingly to current tx gasprice: _usedFunds = _witnetUpgradeReward(_latestQueryId); } else { // Check if latest update ended successfully: if (_latestUpdateStatus == 200) { // If so, remove previous last valid valid query from the WRB: if (__lastValidQueryId > 0) { _witnetDeleteQuery(__lastValidQueryId); } __lastValidQueryId = _latestQueryId; } // Post update request to the WRB: (_latestQueryId, _usedFunds) = _witnetPostRequest(this); // Update latest query id: latestQueryId = _latestQueryId; } // Transfer back unused funds: payable(msg.sender).transfer(msg.value - _usedFunds); if (_usedFunds > 0) { emit PriceFeeding(msg.sender, _latestQueryId, _usedFunds); } } /// Tells whether this contract implements the interface defined by `interfaceId`. /// @dev See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] /// @dev to learn more about how these ids are created. function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { return ( _interfaceId == type(IERC165).interfaceId || _interfaceId == type(IWitnetPriceFeed).interfaceId ); } }
Posts a new price update request to the Witnet Request Board. Requires payment of a fee that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`. If previous update request was not solved yet, calling this method again allows upgrading the update fee if called with a higher `tx.gasprice` value. latest update is still pending, so just raise upgrade reward, accordingly to current tx gasprice: Check if latest update ended successfully: If so, remove previous last valid valid query from the WRB:
function requestUpdate() public payable virtual override { uint _usedFunds; uint _latestQueryId = latestQueryId; uint _latestUpdateStatus = latestUpdateStatus(); if (_latestUpdateStatus == 404) { _usedFunds = _witnetUpgradeReward(_latestQueryId); if (_latestUpdateStatus == 200) { if (__lastValidQueryId > 0) { _witnetDeleteQuery(__lastValidQueryId); } __lastValidQueryId = _latestQueryId; } } if (_usedFunds > 0) { emit PriceFeeding(msg.sender, _latestQueryId, _usedFunds); } }
1,303,523
pragma solidity ^0.4.21; // Open Zeppelin library for preventing overflows and underflows. library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0. uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold. return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ERC20 Token interface. interface IERC20 { function totalSupply() public constant returns (uint256 totalSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); } // Contract onwer restrictions. contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract FidelityPoints is IERC20, Owned { // Overlay of the Safemath library on uint256 datatype using SafeMath for uint256; // Restrinct the usage of a function to a user modifier onlyUser { require(!containsShop(msg.sender)); _; } // Restrinct the usage of a function to a shop modifier onlyShop { require(containsShop(msg.sender)); _; } // Structure of a payment request done by a shop asking money from the ISP. struct EthereumPaymentRequest { address shop; // Ethereum address of the shop, sender of the request. string note; // Additional notes for the admin uint value; // Amount of ethereum to be transfered string shopId; // Id of the shop who is making the request in order to get its data from the database bool completed; // Flag regarding the admin execution of the payment bool rejected; // Flag regarding the approvation status of the request } // Structure of a buy request done by a user for buying a product from a shop. struct BuyingRequest { address user; // Ethereum address of the user, sender of the request. address shop; // Ethereum address of the shop, receiver of the request. string product; // Id of the product object to be bought. string shopEmail; // Email of the shop, used for diplaying the request to its belonging shops. string userId; // Id of the user, used for showing him every request he has performed. uint value; // Tokens used for buying the product, they are sent with the request bool shipped; // Flag regarding the shipment status of the request bool rejected; // Flag regarding the approvation status of the request } // Contract variables. uint public constant INITIAL_SUPPLY = 1000000000000; // Initial supply of tokens: 1.000.000.000.000 uint public _totalSupply = 0; // Total amount of tokens address public owner; // Address of the contract owner address[] public shops; // Array of shop addresses EthereumPaymentRequest[] public ethereumPaymentRequests; // Array of shop payment requests BuyingRequest[] public buyingRequests; // Array of user buy requests // Cryptocurrency characteristics. string public constant symbol = "FID"; // Cryprocurrency symbol string public constant name = "Fido Coin"; // Cryptocurrency name uint8 public constant decimals = 18; // Standard number for Eth Token uint256 public constant RATE = 1000000000000000000; // 1 ETH = 10^18 FID; // Map definions. mapping (address => uint256) public balances; // Map [User,Amount] mapping (address => bool) public shopsMap; // Map [Shop,Official] mapping (address => mapping (address => uint256)) public allowed; // Map [User,[OtherUser,Amount]] // Events definition. // This notify clients about the transfer. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Constructor, set the contract sender/deployer as owner. function FidelityPoints() public { // Check for the null address. require(msg.sender != 0x00); // Update total supply with decimals. _totalSupply = INITIAL_SUPPLY * 10 ** uint256(decimals); // Give an initial supply to the contract creator. balances[msg.sender] = _totalSupply; // Who deploys the contract is the owner. owner = msg.sender; // Add owner in shops Array. shops.push(owner); // add owner in shopsMap. shopsMap[owner] = true; } /****************************************************************************** * Fallback function, a function with no name that gets called. * * whenever you do not actually pass a function name. * * This allow people to just send money directly to the contract address. * ******************************************************************************/ function () public payable { // People will send money directly to the contract address. } /***************************************************************************** * Check if a shop exists. * ******************************************************************************/ function containsShop(address _shop) public view returns (bool) { return shopsMap[_shop]; } /***************************************************************************** * Perform a FIDO token generation. * ******************************************************************************/ function createTokens() public payable onlyOwner { // Check if the amount trasfered is greather than 0. require(msg.value > 0); // Check if the sender address is 0. require(msg.sender != 0x00); // Create tokens from Ether multiplying for 10^18 uint256 tokens = msg.value.mul(RATE); // Add tokens to the buyer account. balances[msg.sender] = balances[msg.sender].add(tokens); // Total supply number increased by the new token creation. _totalSupply = _totalSupply.add(tokens); // Transfer the amount to the owner, auto rollback if the transaction fails. owner.transfer(msg.value); } /***************************************************************************** * Perform a payment with the ETH cryptocurrency. * * * * Return true if success. * * * * @param _to the address of the receiver. * * @param _value amount of ETH transfered. * ******************************************************************************/ function payWithEthereum(address _to, uint256 _value) public payable onlyOwner returns (bool success) { // Check if the amount trasfered is greather than 0. require(msg.value > 0); // Check if the sender is differrent from 0x00. require(msg.sender != 0x00); // Transfer Operation. _to.transfer(_value); return true; } /***************************************************************************** * Return the total supply of the token. * * * * * * Return the value of the variable `_totalSupply`. * ******************************************************************************/ function totalSupply() public constant returns (uint256 totalSupply) { // Value of the contract variable return _totalSupply; } /***************************************************************************** * Return the balance of an account. * * * * Return the amount of money of the `_account`. * * * * @param _account the address of the account of which I want the balance. * ******************************************************************************/ function balanceOf(address _account) public constant returns (uint256 balance) { return balances[_account]; } /***************************************************************************** * Transfer tokens from sender to receiver. * * * * Send `_value` tokens from the msg.sender to the `_to` address. * * * * @param _to the address of the receiver. * * @param _value the amount of points to send. * ******************************************************************************/ function transfer(address _to, uint256 _value) public returns (bool success) { _value = _value * 10 ** uint256(decimals); // Check if the sender has enough. require(balances[msg.sender] >= _value); // Check if the amount trasfered is greather than 0. require(_value > 0); // Prevent transfer to 0x0 address. require(_to != 0x0); // Check for overflows. require(balances[_to] + _value > balances[_to]); // Check for underflows. require(balances[msg.sender] - _value < balances[msg.sender]); // Save for the future assertion. uint previousBalances = balances[msg.sender].add(balances[_to]); // Subtract the token amount from the sender. balances[msg.sender] = balances[msg.sender].sub(_value); // Add the token amount to the recipient. balances[_to] = balances[_to].add(_value); // Emit the Transfer event. emit Transfer(msg.sender, _to, _value); // Asserts are used to use static analysis to find bugs in code. They should never fail. assert(balances[msg.sender].add(balances[_to]) == previousBalances); return true; } /***************************************************************************** * Get the most important token informations * ******************************************************************************/ function getSummary() public view returns (uint, address, string, string, uint8, uint256) { uint exponent = 10 ** uint(decimals); uint256 tokenUnits = _totalSupply / exponent; return( tokenUnits, owner, symbol, name, decimals, RATE ); } /***************************************************************************** * Add a new shop to the collection of official shops * ******************************************************************************/ function addShop(address _newShop) public onlyOwner returns (bool) { // Add shop in shops Array shops.push(_newShop); // Add shop in shopsMap shopsMap[_newShop] = true; return true; } /***************************************************************************** * Returns the number of the official shops * ******************************************************************************/ function getShopsCount() public view returns (uint) { return shops.length; } /***************************************************************************** * Shop create a request to be payed and pay the ISP. * * * * * * @param _value * * @param _note * * @param _shopId * ******************************************************************************/ function createEthereumPaymentRequest(uint _value, string _note, string _shopId) public onlyShop returns (bool) { // Check if the shop has enough token. require(balances[msg.sender] >= _value); // Check if the amount trasfered is greather than 0. require(_value > 0); // Prevent transfer to 0x0 address. require(owner != 0x0); // Check for overflows. require(balances[owner] + _value > balances[owner]); // Check for underflows. require(balances[msg.sender] - _value < balances[msg.sender]); // Create the new EthereumPaymentRequest. EthereumPaymentRequest memory ethereumPaymentRequest = EthereumPaymentRequest({ shop: msg.sender, note: _note, value: _value, shopId: _shopId, completed: false, rejected: false }); // Adding a new ethereum payment request. ethereumPaymentRequests.push(ethereumPaymentRequest); // Value convertion. _value = _value * 10 ** uint256(decimals); // Save for the future assertion. uint previousBalances = balances[msg.sender].add(balances[owner]); // Subtract the token amount from the shop. balances[msg.sender] = balances[msg.sender].sub(_value); // Add the token amount to the contract owner. balances[owner] = balances[owner].add(_value); // Emit the Transfer event. emit Transfer(msg.sender, owner, _value); // Asserts are used to use static analysis to find bugs in code. They should never fail. assert(balances[msg.sender].add(balances[owner]) == previousBalances); return true; } /***************************************************************************** * User create a request to buy a product from a shop. * * * * * * @param _product * * @param _shopEmail * * @param _receiver * * @param _value * * @param _userId * ******************************************************************************/ function createBuyingRequest(string _product, string _shopEmail, address _receiver, uint _value, string _userId) public onlyUser returns (bool) { // Check if the sender has enough. require(balances[msg.sender] >= _value); // Check if the amount trasfered is greather than 0. require(_value > 0); // Prevent transfer to 0x0 address. require(_receiver != 0x0); // Check for overflows. require(balances[_receiver] + _value > balances[_receiver]); // Check for underflows. require(balances[msg.sender] - _value < balances[msg.sender]); // Receiver should be an official shop. require(containsShop(_receiver)); // Create the new BuyingRequest. BuyingRequest memory buyingRequest = BuyingRequest({ user: msg.sender, shop: _receiver, product: _product, shopEmail: _shopEmail, value: _value, userId: _userId, shipped: false, rejected: false }); // Adding a new buy request. buyingRequests.push(buyingRequest); // Value convertion. _value = _value * 10 ** uint256(decimals); // Save for the future assertion. uint previousBalances = balances[msg.sender].add(balances[_receiver]); // Subtract the token amount from the user sender. balances[msg.sender] = balances[msg.sender].sub(_value); // Add the token amount to the shop receiver balances[_receiver] = balances[_receiver].add(_value); // Emit the Transfer event. emit Transfer(msg.sender, _receiver, _value); // Asserts are used to use static analysis to find bugs in code. They should never fail. assert(balances[msg.sender].add(balances[_receiver]) == previousBalances); return true; } /***************************************************************************** * Used for returning ethereum payment requests done by shop one by one. * ******************************************************************************/ function getRequestsCount() public view returns (uint256) { return ethereumPaymentRequests.length; } /***************************************************************************** * Used for returning user buy requests one by one. * ******************************************************************************/ function getUserRequestsBuyCount() public view returns (uint256) { return buyingRequests.length; } /**************************************************************************** * Shop accepts the request and user is notified. * * * * shop ship the product if phisical. * * * * @param _index * *****************************************************************************/ function finalizeUserRequestBuy(uint _index) public onlyShop { BuyingRequest storage buyingRequest = buyingRequests[_index]; // Check if the product of the request is not reject. require(!buyingRequests[_index].rejected); // Check if the product of the request is still not shipped. require(!buyingRequests[_index].shipped); // Set the request to shipped, this must be done after the product is shipped phisically by the shop. buyingRequest.shipped = true; } /**************************************************************************** * Shop rejected the request and user is refunded with tokens * * * * If the product has been shipped it can still be rejected * * tokens should be given back later * * * * @param _index * *****************************************************************************/ function rejectUserRequestBuy(uint _index) public onlyShop { BuyingRequest storage buyingRequest = buyingRequests[_index]; // Check if the product of the request is still not rejected. require(!buyingRequests[_index].rejected); // Check if the product of the request is still not shipped. require(!buyingRequests[_index].shipped); // Value convertion uint value = buyingRequest.value * 10 ** uint256(decimals); // Save for the future assertion. uint previousBalances = balances[buyingRequest.shop].add(balances[buyingRequest.user]); // Subtract the token amount from the shop. balances[buyingRequest.shop] = balances[buyingRequest.shop].sub(value); // Give back the token amount to the user. balances[buyingRequest.user] = balances[buyingRequest.user].add(value); // Emit the Transfer event. emit Transfer(buyingRequest.shop, buyingRequest.user, value); // Asserts are used to use static analysis to find bugs in code. They should never fail. assert(balances[buyingRequest.shop].add(balances[buyingRequest.user]) == previousBalances); // Set the request as rejected. buyingRequest.rejected = true; } /**************************************************************************** * Owner accepts the request and shop is payed in eth. * * * * Owner finalize the request manually. * * * * @param _index * *****************************************************************************/ function finalizeRequestEthereum(uint _index) public onlyOwner payable { EthereumPaymentRequest storage ethereumPaymentRequest = ethereumPaymentRequests[_index]; // Check if not rejected. require(!ethereumPaymentRequests[_index].rejected); // Check if still not finalized. require(!ethereumPaymentRequests[_index].completed); // Convert Token to ethereum. uint256 ethValue = ethereumPaymentRequest.value.div(RATE); // Trasfer ethereum amount to the shop. ethereumPaymentRequest.shop.transfer(ethValue); // Set shop request status to completed. ethereumPaymentRequest.completed = true; } /**************************************************************************** * Owner reject the request and shop is refunded with tokens * * * * @param _index * *****************************************************************************/ function rejectRequestEthereum(uint _index) public onlyOwner { EthereumPaymentRequest storage ethereumPaymentRequest = ethereumPaymentRequests[_index]; // Check if already finalized. require(!ethereumPaymentRequests[_index].completed); // Check if the product of the request is still not rejected. require(!ethereumPaymentRequests[_index].rejected); // Value convertion. uint value = ethereumPaymentRequest.value * 10 ** uint256(decimals); // Save for the future assertion. uint previousBalances = balances[owner].add(balances[ethereumPaymentRequest.shop]); // Subtract the token amount from the owner. balances[owner] = balances[owner].sub(value); // Give bacje the token amount to the shop. balances[ethereumPaymentRequest.shop] = balances[ethereumPaymentRequest.shop].add(value); // Emit the Transfer event. emit Transfer(owner, ethereumPaymentRequest.shop, value); // Asserts are used to use static analysis to find bugs in code. They should never fail. assert(balances[owner].add(balances[ethereumPaymentRequest.shop]) == previousBalances); // Set the shop payment request as rejected. ethereumPaymentRequest.rejected = true; } }
Used for returning ethereum payment requests done by shop one by one. /
function getRequestsCount() public view returns (uint256) { return ethereumPaymentRequests.length; }
12,744,826
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './ITickMath.sol'; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 contract TickMath is ITickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 public constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 public constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 public constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 public constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (uint160(1) << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) public pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; uint256 f; f = 0; if (r > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) f = 1 << 7; msb = msb | f; r = r >> f; f = 0; if (r > 0xFFFFFFFFFFFFFFFF) f = 1 << 6; msb = msb | f; r = r >> f; f = 0; if (r > 0xFFFFFFFF) f = 1 << 5; msb = msb | f; r = r >> f; f = 0; if (r > 0xFFFF) f = 1 << 4; msb = msb | f; r = r >> f; f = 0; if (r > 0xFF) f = 1 << 3; msb = msb | f; r = r >> f; f = 0; if (r > 0xF) f = 1 << 2; msb = msb | f; r = r >> f; f = 0; if (r > 0x3) f = 1 << 1; msb = msb | f; r = r >> f; f = 0; if (r > 0x1) f = 1; msb = msb | f; if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 63); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 62); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 61); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 60); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 59); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 58); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 57); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 56); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 55); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 54); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 53); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 52); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 51); r = r >> f; r = (r * r) >> 127; f = r >> 128; log_2 = log_2 | (int256(f) << 50); int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : (getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow); } }
The minimum tick that may be passed to getSqrtRatioAtTick computed from log base 1.0001 of 2-128 The maximum tick that may be passed to getSqrtRatioAtTick computed from log base 1.0001 of 2128 The minimum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) The maximum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) Calculates sqrt(1.0001^tick) 2^96 Throws if |tick| > max tick tick The input tick for the above formula return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) at the given tick this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. we then downcast because we know the result always fits within 160 bits due to our tick input constraint we round up in the division so getTickAtSqrtRatio of the output price is always consistent
function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (uint160(1) << 32) == 0 ? 0 : 1)); }
5,432,861
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BlacklisterRole Contract /// @notice Only administrators can update the black lister roles /// @dev Keeps track of black listers and can check if an account is authorized contract BlacklisterRole is OwnerRole { event BlacklisterAdded( address indexed addedBlacklister, address indexed addedBy ); event BlacklisterRemoved( address indexed removedBlacklister, address indexed removedBy ); Role private _Blacklisters; /// @dev Modifier to make a function callable only when the caller is a black lister modifier onlyBlacklister() { require(isBlacklister(msg.sender), "BlacklisterRole missing"); _; } /// @dev Public function returns `true` if `account` has been granted a black lister role function isBlacklister(address account) public view returns (bool) { return _has(_Blacklisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function _addBlacklister(address account) internal { _add(_Blacklisters, account); emit BlacklisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a black lister /// @param account The address removed as a black lister function _removeBlacklister(address account) internal { _remove(_Blacklisters, account); emit BlacklisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function addBlacklister(address account) external onlyOwner { _addBlacklister(account); } /// @dev Public function that removes an account from being a black lister /// @param account The address removed as a black lister function removeBlacklister(address account) external onlyOwner { _removeBlacklister(account); } uint256[49] private __gap; }
Public function that adds an address as a black lister account The address that is guaranteed black lister authorization
function addBlacklister(address account) external onlyOwner { _addBlacklister(account); }
1,796,372
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: @openzeppelin/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: @openzeppelin/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } // File: contracts/NasiToken.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.14; contract NasiToken is Ownable, ERC20Detailed('NasiToken', 'NAS', 18), ERC20Pausable, ERC20Burnable, ERC20Mintable { function mint(address _to, uint256 _amount) public onlyMinter returns (bool) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); return true; } mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "NASI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "NASI::delegateBySig: invalid nonce"); require(now <= expiry, "NASI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "NASI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying NASIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "NASI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/NasiLiquidityPoolFactory.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.14; interface IMigrator { /** * Perform LP token migration from legacy UniswapV2 to NasiSwap. * Take the current LP token address and return the new LP token address. * Migrator should have full access to the caller's LP token. * XXX Migrator must have allowance access to UniswapV2 LP tokens. * NasiSwap must mint EXACTLY the same amount of NasiSwap LP tokens or * else something bad will happen. Traditional UniswapV2 does not * do that so be careful! */ function migrate(address token) external returns (address); } contract NasiLiquidityPoolFactory is Ownable { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @param amountOfLpToken * @param rewardDebt */ struct UserInfo { uint256 amountOfLpToken; uint256 rewardDebt; } struct PoolInfo { address lpTokenAddress; uint256 allocationPoint; uint256 lastRewardBlock; uint256 accumulatedNasiPerShare; } NasiToken public nasiToken; uint256 public nasiPerBlock; uint256 public endBlock; uint256 public endBlockWeek1; uint256 public endBlockWeek2; uint256 public endBlockWeek3; uint256 public endBlockWeek4; uint256 public poolCounter; address public migrator; address public devaddr; mapping (uint256 => PoolInfo) public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocationPoint; uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _nasiAddress, address _devaddr, uint256 _nasiPerBlock, uint256 _startBlock ) public { nasiToken = NasiToken(_nasiAddress); devaddr = _devaddr; nasiPerBlock = _nasiPerBlock; startBlock = _startBlock; endBlockWeek1 = _startBlock.add(45500); endBlockWeek2 = endBlockWeek1.add(45500); endBlockWeek3 = endBlockWeek2.add(45500); endBlockWeek4 = endBlockWeek3.add(45500); endBlock = _startBlock.add(1137500); } /** * @notice Set the migrator contract. Can only be called by the owner. */ function setMigrator(address _migrator) public onlyOwner { require(_migrator != address(0), 'Migrator can not equal address0'); migrator = _migrator; } /** * @notice Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. */ function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = IERC20(pool.lpTokenAddress); uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); address newLpToken = IMigrator(migrator).migrate(pool.lpTokenAddress); require(bal == IERC20(newLpToken).balanceOf(address(this)), "migrate: bad"); pool.lpTokenAddress = newLpToken; } /** * @notice Deposit LP tokens to Factory for nasi allocation. */ function deposit(uint256 _pid, uint256 _amount) public { require(_pid <= poolCounter, 'Invalid pool id!'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amountOfLpToken > 0) { uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); if(pending > 0) { _safeNasiTransfer(msg.sender, pending); } } IERC20(pool.lpTokenAddress).safeTransferFrom(address(msg.sender), address(this), _amount); user.amountOfLpToken = user.amountOfLpToken.add(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); emit Deposit(msg.sender, _pid, _amount); } /** * @notice Add a new lp to the pool. Can only be called by the owner. */ function addLpToken(uint256 _allocationPoint, address _lpTokenAddress, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } poolCounter++; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocationPoint = totalAllocationPoint.add(_allocationPoint); poolInfo[poolCounter] = PoolInfo( _lpTokenAddress, _allocationPoint, lastRewardBlock, 0 ); } function massUpdatePools() public { for (uint256 _pid = 1; _pid <= poolCounter; _pid++) { updatePool(_pid); } } /** * @notice Update reward variables of the given pool to be up-to-date. */ function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = IERC20(pool.lpTokenAddress).balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getBonusMultiplier(pool.lastRewardBlock, block.number); uint256 nasiReward = multiplier.mul(nasiPerBlock).mul(pool.allocationPoint).div(totalAllocationPoint); nasiToken.mint(address(this), nasiReward); nasiToken.mint(devaddr, nasiReward.div(50)); pool.accumulatedNasiPerShare = pool.accumulatedNasiPerShare.add(nasiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } /** * @notice Get the bonus multiply ratio at the initial time. */ function getBonusMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 week1 = _from <= endBlockWeek1 && _to > startBlock ? (Math.min(_to, endBlockWeek1) - Math.max(_from, startBlock)).mul(16) : 0; uint256 week2 = _from <= endBlockWeek2 && _to > endBlockWeek1 ? (Math.min(_to, endBlockWeek2) - Math.max(_from, endBlockWeek1)).mul(8) : 0; uint256 week3 = _from <= endBlockWeek3 && _to > endBlockWeek2 ? (Math.min(_to, endBlockWeek3) - Math.max(_from, endBlockWeek2)).mul(4) : 0; uint256 week4 = _from <= endBlockWeek4 && _to > endBlockWeek3 ? (Math.min(_to, endBlockWeek4) - Math.max(_from, endBlockWeek3)).mul(2) : 0; uint256 end = _from <= endBlock && _to > endBlockWeek4 ? (Math.min(_to, endBlock) - Math.max(_from, endBlockWeek4)) : 0; return week1.add(week2).add(week3).add(week4).add(end); } function pendingNasi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accumulatedNasiPerShare = pool.accumulatedNasiPerShare; uint256 lpSupply = IERC20(pool.lpTokenAddress).balanceOf(address(this)); if (lpSupply == 0) { return 0; } if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplierBonus = getBonusMultiplier(pool.lastRewardBlock, block.number); uint256 nasiReward = multiplierBonus.mul(nasiPerBlock).mul(pool.allocationPoint).div(totalAllocationPoint); accumulatedNasiPerShare = accumulatedNasiPerShare.add(nasiReward.mul(1e12).div(lpSupply)); } return (user.amountOfLpToken.mul(accumulatedNasiPerShare).sub(user.rewardDebt).div(1e12)); } /** * @notice Withdraw LP tokens from Factory */ function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amountOfLpToken >= _amount, "Not enough funds!"); updatePool(_pid); uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); _safeNasiTransfer(msg.sender, pending); user.amountOfLpToken = user.amountOfLpToken.sub(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amountOfLpToken; user.amountOfLpToken = 0; user.rewardDebt = 0; IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Update the given pool's NASI allocation point. Can only be called by the owner. function setAllocationPoint(uint256 _pid, uint256 _allocationPoint, bool _withUpdate) public onlyOwner { require(_pid <= poolCounter, 'Invalid pool id!'); if (_withUpdate) { massUpdatePools(); } totalAllocationPoint = totalAllocationPoint.sub(poolInfo[_pid].allocationPoint).add(_allocationPoint); poolInfo[_pid].allocationPoint = _allocationPoint; } function _safeNasiTransfer(address _to, uint256 _amount) internal { uint256 nasiBalance = nasiToken.balanceOf(address(this)); if (_amount > nasiBalance) { nasiToken.transfer(_to, nasiBalance); } else { nasiToken.transfer(_to, _amount); } } function _safeNasiBurn(uint256 _amount) internal { uint256 nasiBalance = nasiToken.balanceOf(address(this)); if (_amount > nasiBalance) { nasiToken.burn(nasiBalance); } else { nasiToken.burn(_amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Get the bonus multiply ratio at the initial time./
function getBonusMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 week1 = _from <= endBlockWeek1 && _to > startBlock ? (Math.min(_to, endBlockWeek1) - Math.max(_from, startBlock)).mul(16) : 0; uint256 week2 = _from <= endBlockWeek2 && _to > endBlockWeek1 ? (Math.min(_to, endBlockWeek2) - Math.max(_from, endBlockWeek1)).mul(8) : 0; uint256 week3 = _from <= endBlockWeek3 && _to > endBlockWeek2 ? (Math.min(_to, endBlockWeek3) - Math.max(_from, endBlockWeek2)).mul(4) : 0; uint256 week4 = _from <= endBlockWeek4 && _to > endBlockWeek3 ? (Math.min(_to, endBlockWeek4) - Math.max(_from, endBlockWeek3)).mul(2) : 0; uint256 end = _from <= endBlock && _to > endBlockWeek4 ? (Math.min(_to, endBlock) - Math.max(_from, endBlockWeek4)) : 0; return week1.add(week2).add(week3).add(week4).add(end); }
55,011
pragma experimental ABIEncoderV2; contract Registry { ////////////////////// // REGISTRY FUNCTIONS // ///////////////////////// // address internal owner; //operator //Each smart meter has a user attached mapping(address => address) public registry; // 1: Certificate Authority // 2: Smart meter // 3: Users mapping(address => uint8) public identity; constructor() public { identity[msg.sender] = 1; } //Register a new administrator address function registerAuthority(address _a) public { identity[_a] = 1; } /* Register of a smart meter of an owner (account) Assumptions: - One owner can have more than one smart meter. Differet users are idetified with unique ID. - Smart meter have an id (identity 2) - Users have an ID (identity 3) */ function register(address _sm, address _user) onlyAuthorities public { //Check if the entered smart meter exists. require(!registered(_sm), "Smart Meter already registered"); // registry[smartMeter] = owner; identity[_sm] = 2; identity[_user] = 3; registry[_sm] = _user; } // Check if a specific address is mapped to the smart meter// function check_registry(address _sm, address _user) public view returns (bool) { if (registry[_sm] == _user) { return true; } return false; } // Check if the smart meter is registered. function registered(address _sm) public view returns (bool) { if (registry[_sm] == address(0)) { return false; } return true; } // MODIFIERS // ========================== modifier onlyAuthorities() { if (identity[msg.sender] != 1) revert(); _; } modifier onlySmartMeters() { if (identity[msg.sender] != 2) revert(); _; } modifier onlyUsers() { if (identity[msg.sender] != 3) revert(); _; } }
/Check if the entered smart meter exists. registry[smartMeter] = owner;
function register(address _sm, address _user) onlyAuthorities public { require(!registered(_sm), "Smart Meter already registered"); identity[_sm] = 2; identity[_user] = 3; registry[_sm] = _user; }
6,479,340
./full_match/97/0x41688cbc29210499f83731dC381fE65f733117ab/sources/project_/contracts/diamond/libraries/LibPriceFacade.sol
todo: 增加对价格校验的逻辑,和 chainlink 拿价格比较相差幅度
function requestPriceCallback(bytes32 requestId, uint256 price) internal { PriceFacadeStorage storage pfs = priceFacadeStorage(); PendingPrice memory pendingPrice = pfs.pendingPrices[requestId]; bytes32[] memory ids = pendingPrice.ids; require(pendingPrice.blockNumber > 0 && ids.length > 0, "LibPriceFacade: requestId does not exist"); LatestCallbackPrice storage cachePrice = pfs.callbackPrices[pendingPrice.token]; cachePrice.timestamp = block.timestamp; cachePrice.price = price; for (uint i; i < ids.length;) { LibTrading.openMarketTradeCallback(ids[i], price); unchecked { i++; } } emit PriceUpdated(msg.sender, requestId, pendingPrice.token, price); }
3,276,838
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 999900000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); // fetch all needed data // using LTV as tokenLiquidationThreshold (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLiquidationThreshold,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLiquidationThreshold,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLiquidationThreshold); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return totalCollateralETH; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLiquidationThreshold, totalCollateralETH), wmul(tokenLiquidationThreshold, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLiquidationThreshold)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLiquidationThreshold) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice), NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice), NINETY_NINE_PERCENT_WEI); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] < _rates[minIndex]) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public view virtual returns(uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { // address public constant ETH_FLIPPER = 0xd8a04F5412223F513DC55F839574430f5EC15531; // address public constant BAT_FLIPPER = 0xaA745404d55f88C108A28c86abE7b5A1E7817c07; // address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; // address public constant ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; // address public constant BAT_JOIN = 0x3D0B1912B66114d4096F48A8CEe3A56C231772cA; // bytes32 public constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; // bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; // address public constant SAVER_EXCHANGE = 0x606e9758a39d2d7fA7e70BC68E6E7D9b02948962; // function daiBid(uint _bidId, bool _isEth, uint _amount) public { // uint tendAmount = _amount * (10 ** 27); // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // joinDai(_amount); // (, uint lot, , , , , , ) = Flipper(flipper).bids(_bidId); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).tend(_bidId, lot, tendAmount); // } // function collateralBid(uint _bidId, bool _isEth, uint _amount) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // uint bid; // (bid, , , , , , , ) = Flipper(flipper).bids(_bidId); // joinDai(bid / (10**27)); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).dent(_bidId, _amount, bid); // } // function closeBid(uint _bidId, bool _isEth) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // Flipper(flipper).deal(_bidId); // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function closeBidAndExchange( // uint _bidId, // bool _isEth, // uint256[4] memory _data, // address _exchangeAddress, // bytes memory _callData // ) // public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // (uint bidAmount, , , , , , , ) = Flipper(flipper).bids(_bidId); // Flipper(flipper).deal(_bidId); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(address(this), (bidAmount / 10**27)); // address srcToken = _isEth ? KYBER_ETH_ADDRESS : address(Gem(join).gem()); // uint daiAmount = swap( // _data, // srcToken, // DAI_ADDRESS, // _exchangeAddress, // _callData // ); // ERC20(DAI_ADDRESS).transfer(msg.sender, daiAmount); // } // function exitCollateral(bool _isEth) public { // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function exitDai() public { // uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(DAI_JOIN); // Gem(DAI_JOIN).exit(msg.sender, amount); // } // function withdrawToken(address _token) public { // uint balance = ERC20(_token).balanceOf(address(this)); // ERC20(_token).transfer(msg.sender, balance); // } // function withdrawEth() public { // uint balance = address(this).balance; // msg.sender.transfer(balance); // } // function joinDai(uint _amount) internal { // uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // if (_amount > amountInVat) { // uint amountDiff = (_amount - amountInVat) + 1; // ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); // ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); // Join(DAI_JOIN).join(address(this), amountDiff); // } // } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { address payable public constant MCD_CREATE_FLASH_LOAN = 0xb09bCc172050fBd4562da8b229Cf3E45Dc3045A6; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).transferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).transfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract LoanShifterTaker is AdminAuth, ProxyPermission { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_loanShift, _exchangeData); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); uint loanAmount = _loanShift.debtAmount; if (_loanShift.wholeDebt) { loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { approvedCallers[msg.sender] = true; aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x9D266997bc73B27d4302E711b55FD78B5278e1De; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); address payable payableProxy = payable(proxy); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payableProxy).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy uint256 collateralAmount = ERC20(aCollateralToken).balanceOf(user); ERC20(aCollateralToken).safeTransferFrom(user, proxy, collateralAmount); // enable as collateral DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateral(address)", collateralToken)); // withdraw deposited eth DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x56AC1EFC17ecDe083889520137B0cfb30d2cF384; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 80000000000; // 80 gwei uint public REPAY_GAS_COST = 2200000; uint public BOOST_GAS_COST = 1700000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { approvedCallers[msg.sender] = true; compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, address(this).balance, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, address(this).balance, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr); } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2 { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_srcAddr, _destAddr, _destAmount); uint256 srcAmount = wmul(_destAmount, srcRate); rate = getSellRate(_destAddr, _srcAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == KYBER_ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2 { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { address srcAddr = ethToWethAddr(_srcAddr); if (srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(srcAddr).safeTransfer(msg.sender, ERC20(srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2 { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { approvedCallers[msg.sender] = true; monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai }); address collAddr = closeCDP(closeData, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); sendLeftover(collAddr, DAI_ADDRESS, tx.origin); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData ) internal returns (address) { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; address user = DSProxy(payable(_closeData.proxy)).owner(); if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, user); } else { dfsFee = getFee(_closeData.daiAmount, user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = address(Join(_closeData.joinAddr).gem()); require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); return tokenAddr; } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address payable public constant MCD_CLOSE_FLASH_LOAN = 0xdFccc9C59c7361307d47c558ffA75840B32DbA29; address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData ) public payable { MCD_CLOSE_FLASH_LOAN.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(MCD_CLOSE_FLASH_LOAN, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { Join(_joinAddr).gem().approve(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); // if (paramData.swapType == 1) { // COLL_SWAP // exchangeData.srcAmount = getBalance(exchangeData.srcAddr); // (, uint amount) = _sell(exchangeData); // sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); // } else if (paramData.swapType == 2) { // DEBT_SWAP // exchangeData.destAmount = (_amount + _fee); // _buy(exchangeData); // } else { // NO_SWAP just send tokens to proxy // sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); // } // // Execute the Open operation (Skip if it's debt swap) // if (paramData.swapType != 2) { // DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // } // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } // Call specific function if it's a debt swap if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getWholeDebt(uint _cdpId, address _joinAddr) public virtual returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); } // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); IAToken(aTokenCollateral).redeem(_data.srcAmount); // swap (, uint256 destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE); _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, uint256 destAmount) = _sell(_data); if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); // Swap (, uint sellAmount) = _sell(exchangeData); // DFS fee getFee(sellAmount, exchangeData.destAddr, proxyAddr); // Send amount to DSProxy sendToProxy(proxyAddr, exchangeData.destAddr); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(compOpenProxy, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (address payable, bytes memory proxyData, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); return (payable(proxy), proxyData, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x6423708d6B84Af237Ab309dF49f6b8Fb751f28FB; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xBD3140131dEd4426694257411d564791Cc36D382; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); if (_exData.srcAmount <= maxColl) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); if (_exData.srcAmount <= maxBorrow) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
write in the exact amount we are selling/buing in an order check to see if any _src tokens are left over after exchange convert weth -> eth if needed
function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { tokensLeft = getBalance(_exData.srcAddr); if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } tokensSwaped = getBalance(_exData.destAddr); } return (success, tokensSwaped, tokensLeft); }
7,432,378
./partial_match/1/0x647bFB48465F50b8244CaC864DBf445cbcdF93fb/sources/XANALand.sol
Mint Common CategoryCheck user buy limit merkle tcheck user purchase amountMinting Land NFTs as per sent amount above
function mintLand(string memory rarity,uint256 _mintAmount, uint256 _size, bytes32[] calldata proof, bool isLimit, uint256 whitelistType) checkSupply(_mintAmount,_size, rarity) external payable { require(rates[_size][rarity].valid, "XanaLand: Plot size not valid" ); require(isWhitelistFor[whitelistType][rarity], "XanaLand: Invalid"); if(status == 2) require(whitelistType == 0, "XanaLand: only public sale"); else require(whitelistType != 0, "XanaLand: "); require(checkWhiteList(_mintAmount, proof, whitelistType, isLimit), "XanaLand: Not whitelisted"); _userBought[whitelistType][msg.sender] += _mintAmount; require(msg.value >= SafeMath.mul(rates[_size][rarity].cost,_mintAmount), "XanaLand: Paid amount insufficient"); mintNFT(msg.sender,_mintAmount, rarity, _size, false); }
2,765,805
pragma solidity ^0.4.24; contract RSEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularLastUnicorn is RSEvents {} contract LastUnicorn is modularLastUnicorn { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; // TODO: check address UnicornInterfaceForForwarder constant private TeamUnicorn = UnicornInterfaceForForwarder(0xBB14004A6f3D15945B3786012E00D9358c63c92a); UnicornBookInterface constant private UnicornBook = UnicornBookInterface(0x98547788f328e1011065E4068A8D72bacA1DDB49); string constant public name = "LastUnicorn Round #1"; string constant public symbol = "RS1"; uint256 private rndGap_ = 0; // TODO: check time uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => RSdatasets.PlayerRounds) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** RSdatasets.Round public round_; // round data //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 60; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with LastUnicorn */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_.end && round_.ended == false && round_.plyr != 0) { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_.ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = UnicornBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = UnicornBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = UnicornBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // grab time uint256 _now = now; if (_now < round_.end) if (_now > round_.strt + rndGap_) return( (round_.end).sub(_now) ); else return( (round_.strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_.end && round_.ended == false && round_.plyr != 0) { // if player is winner if (round_.plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_.pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID) private view returns(uint256) { return( ((((round_.mask).add(((((round_.pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_.keys))).mul(plyrRnds_[_pID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { return ( round_.keys, //0 round_.end, //1 round_.strt, //2 round_.pot, //3 round_.plyr, //4 plyr_[round_.plyr].addr, //5 plyr_[round_.plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { // grab time uint256 _now = now; // if round is active if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) { // call core core(_pID, msg.value, _affID, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_.end && round_.ended == false) { // end the round (distributes pot) & start new round round_.ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_) private { // grab time uint256 _now = now; // if round is active if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_pID, _eth, _affID, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_.end && round_.ended == false) { // end the round (distributes pot) & start new round round_.ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RSEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_.eth < 100000000000000000000 && plyrRnds_[_pID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_.eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys); // set new leaders if (round_.plyr != _pID) round_.plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID].keys = _keys.add(plyrRnds_[_pID].keys); plyrRnds_[_pID].eth = _eth.add(plyrRnds_[_pID].eth); // update round round_.keys = _keys.add(round_.keys); round_.eth = _eth.add(round_.eth); // distribute eth _eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID) private view returns(uint256) { return((((round_.mask).mul(plyrRnds_[_pID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(UnicornBook), "only UnicornBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(UnicornBook), "only UnicornBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of LastUnicorn if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = UnicornBook.getPlayerID(msg.sender); bytes32 _name = UnicornBook.getPlayerName(_pID); uint256 _laff = UnicornBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // grab our winning player and team id's uint256 _winPID = round_.plyr; // grab our pot amount // add airdrop pot into the final pot uint256 _pot = round_.pot + airDropPot_; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys); uint256 _dust = _gen.sub((_ppt.mul(round_.keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(TeamUnicorn).call.value(_com)(bytes4(keccak256("deposit()")))) { _gen = _gen.add(_com); _com = 0; } // distribute gen portion to key holders round_.mask = _ppt.add(round_.mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_.end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = 0; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID) private { uint256 _earnings = calcUnMaskedEarnings(_pID); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID].mask = _earnings.add(plyrRnds_[_pID].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_.end && round_.plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_.end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_.end = _newTime; else round_.end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth * 5 / 100; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } if (!address(TeamUnicorn).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures TeamUnicorn cannot influence the outcome // bank migrations by breaking outgoing transactions. } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (20%) uint256 _pot = (_eth.mul(20) / 100); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_.pot = _pot.add(_dust).add(round_.pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys); round_.mask = _ppt.add(round_.mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID].mask = (((round_.mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_.keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate // TODO: set owner require( (msg.sender == 0xcD0fce8d255349092496F131f2900DF25f0569F8), "only owner can activate" ); // can only be ran once require(activated_ == false, "LastUnicorn already activated"); // activate the contract activated_ = true; round_.strt = now - rndGap_; round_.end = now + rndInit_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RSdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RSKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface UnicornInterfaceForForwarder { function deposit() external payable returns(bool); } interface UnicornBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
decides if round end needs to be run & new round started. and if player unmasked earnings from previously played rounds need to be moved./ set the joined round bool to true
function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); }
533,578
pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import "./OpenOraclePriceData.sol"; import "./verifier.sol"; struct Observation { uint timestamp; uint acc; } struct Proof { uint[2] a; uint[2][2] b; uint[2] c; } struct PublicInput { uint[3] in; } contract OracleView { using FixedPoint for *; /// @notice The Open Oracle Price Data contract OpenOraclePriceData public immutable priceData; /// @notice The number of wei in 1 ETH uint public constant ethBaseUnit = 1e18; /// @notice A common scaling factor to maintain precision uint public constant expScale = 1e18; /// @notice The Open Oracle Reporter address public immutable reporter; /// @notice The highest ratio of the new price to the anchor price that will still trigger the price to be updated uint public immutable upperBoundAnchorRatio; /// @notice The lowest ratio of the new price to the anchor price that will still trigger the price to be updated uint public immutable lowerBoundAnchorRatio; /// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced uint public immutable anchorPeriod; /// @notice Official prices by symbol hash mapping(bytes32 => uint) public prices; /// @notice Circuit breaker for using anchor price oracle directly, ignoring reporter bool public reporterInvalidated; /// @notice The old observation for each symbolHash mapping(bytes32 => Observation) public oldObservations; /// @notice The new observation for each symbolHash mapping(bytes32 => Observation) public newObservations; /// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor event PriceGuarded(string symbol, uint reporter, uint anchor); /// @notice The event emitted when the stored price is updated event PriceUpdated(string symbol, uint price); /// @notice The event emitted when anchor price is updated event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp); /// @notice The event emitted when the uniswap window changes event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice); /// @notice The event emitted when reporter invalidates itself event ReporterInvalidated(address reporter); bytes32 constant ethHash = keccak256(abi.encodePacked("ETH")); bytes32 constant rotateHash = keccak256(abi.encodePacked("rotate")); /** * @notice Construct a uniswap anchored view for a set of token configurations * @dev Note that to avoid immature TWAPs, the system must run for at least a single anchorPeriod before using. * @param reporter_ The reporter whose prices are to be used * @param anchorToleranceMantissa_ The percentage tolerance that the reporter may deviate from the uniswap anchor * @param anchorPeriod_ The minimum amount of time required for the old uniswap price accumulator to be replaced * @param configs The static token configurations which define what prices are supported and how */ constructor(OpenOraclePriceData priceData_, address reporter_ Verifier verifier_) public { priceData = priceData_; reporter = reporter_; verifier = verifier_; } /** * @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor * @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view. * @param messages The messages to post to the oracle * @param signatures The signatures for the corresponding messages * @param symbols The symbols to compare to anchor for authoritative reading */ function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols, Proof[] proofs, PublicInput[] inputs) external { require(messages.length == signatures.length, "messages and signatures must be 1:1"); // Save the prices for (uint i = 0; i < messages.length; i++) { priceData.put(messages[i], signatures[i], proofs[i], inputs[i]); } } /** * @notice Use priceData.getPriceRange() directly * @param source The verifiable author of the data * @param key The selector for the value to return (symbol in case of uniswap) * @return Price range denominated in USD, with 6 decimals */ function price(address source, string calldata key) external view returns (uint) { uint64 min; uint64 max; (min, max) = getPriceRange(source, key); return (min, max); } }
Post open oracle reporter prices, and recalculate stored price by comparing to anchor We let anyone pay to post anything, but only prices from configured reporter will be stored in the view. messages The messages to post to the oracle signatures The signatures for the corresponding messages symbols The symbols to compare to anchor for authoritative reading/ Save the prices
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols, Proof[] proofs, PublicInput[] inputs) external { require(messages.length == signatures.length, "messages and signatures must be 1:1"); for (uint i = 0; i < messages.length; i++) { priceData.put(messages[i], signatures[i], proofs[i], inputs[i]); } }
12,656,834
./partial_match/1/0xd3B5AD4979788Cf23cBE0704C2Cd2F0629e521b6/sources/LiquidityMining.sol
function used to calculate the reward in a locked liquidity mining setup. setupIndex liquidity mining setup index. mainTokenAmount amount of main token. isPartial if we're calculating a partial reward. positionId id of the position (used for the partial reward). return reward total reward for the liquidity mining position extension. return relativeRewardPerBlock returned for the pinned free setup balancing./ retrieve the position calculate the reward check if main token amount is less than the stakeable liquidity get amount of remaining blocks get total reward still available (= 0 if rewardPerBlock = 0) calculate relativeRewardPerBlock check if rewardPerBlock is greater than 0 calculate reward by multiplying relative reward per block and the remaining blocks check if the reward is still available
function calculateLockedLiquidityMiningSetupReward(uint256 setupIndex, uint256 mainTokenAmount, bool isPartial, uint256 positionId) public view returns(uint256 reward, uint256 relativeRewardPerBlock) { if (isPartial) { LiquidityMiningPosition memory liquidityMiningPosition = _positions[positionId]; reward = (block.number >= liquidityMiningPosition.setupEndBlock) ? liquidityMiningPosition.reward : ((block.number - liquidityMiningPosition.creationBlock) * liquidityMiningPosition.lockedRewardPerBlock); LiquidityMiningSetup memory setup = _setups[setupIndex]; require(mainTokenAmount <= setup.maximumLiquidity - setup.currentStakedLiquidity, "Invalid liquidity"); uint256 remainingBlocks = block.number > setup.endBlock ? 0 : setup.endBlock - block.number; require(remainingBlocks > 0, "Setup ended"); require(setup.rewardPerBlock * remainingBlocks > 0, "No rewards"); relativeRewardPerBlock = (setup.rewardPerBlock * ((mainTokenAmount * 1e18) / setup.maximumLiquidity)) / 1e18; require(relativeRewardPerBlock > 0, "Invalid rpb"); reward = relativeRewardPerBlock * remainingBlocks; } }
4,218,368
pragma solidity ^0.4.0; /** * @title Eliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d. */ library ECRecovery { /* * Internal functions */ /** * @dev Recover signer address from a message by using their signature. * @param _hash Hash of the signed message * @param _sig Signature over the signed message. * @return Address that signed the hash. */ function recover(bytes32 _hash, bytes _sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length. if (_sig.length != 65) { revert("Invalid signature length."); } // Divide the signature in v, r, and s variables. assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions. if (v < 27) { v += 27; } // If the version is correct return the signer address. if (v != 27 && v != 28) { revert("Invalid signature version."); } else { return ecrecover(_hash, v, r, s); } } }
Internal functions/ Recover signer address from a message by using their signature. _hash Hash of the signed message _sig Signature over the signed message. return Address that signed the hash./ Check the signature length. Divide the signature in v, r, and s variables. Version of signature should be 27 or 28, but 0 and 1 are also possible versions. If the version is correct return the signer address.
function recover(bytes32 _hash, bytes _sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { revert("Invalid signature length."); } assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { revert("Invalid signature version."); return ecrecover(_hash, v, r, s); } }
5,547,029
./partial_match/4/0x31684C768A023000aC09D611D18a939D2f2C8728/sources/ExchangeRates.sol
fetch all flags at once do one lookup of the rate & time to minimize gas
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint256[] memory rates, bool anyRateInvalid) { rates = new uint256[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint256 i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime( currencyKeys[i] ); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "dUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } }
8,726,167
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./RandomNumber.sol"; import "./ChainLink.sol"; abstract contract MillionDollarUtils is Aggregator, Ownable, RandomNumber {} contract MillionDollarMint is ERC721Enumerable, MillionDollarUtils { bool public saleIsActive = false; uint256 public constant PRICE = 0.075 ether; uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MAX_PUBLIC_MINT = 10; bool public IS_DRAWN = false; address public winner; modifier soldOut { require(totalSupply() == 10000, "Collection not sold out"); _; } constructor() ERC721("MDM Ticket", "MDM") {} function setSaleState(bool newState) public onlyOwner { saleIsActive = newState; } function mint(uint16 amount) public payable { uint256 ts = totalSupply(); uint256 tsAmount = ts + amount; require(saleIsActive, "Sale not active"); require(amount <= MAX_PUBLIC_MINT, "Max 10 per txn"); require(tsAmount < 10000, "More than total supply"); uint256 price = amount * PRICE; if (tsAmount <= 1000) { price = 0 ether; } else if(tsAmount > 1000 && tsAmount <= 1009) { price = (tsAmount - 1000) * PRICE; } if(tsAmount > 1000) { require(msg.value >= price, "Not enough ether sent"); } for (uint256 i; i < amount ; i++) { _safeMint(msg.sender, ts + i); } if (msg.value > price) { (bool success, ) = payable(msg.sender).call{value: msg.value - price}(""); require(success, "Transfer failed"); } } receive() external payable {} // NOTE: Get the chain link latest price from: https://docs.chain.link/docs/get-the-latest-price/ function previewEthValue(int256 _ethprice) public view returns(int256){ int256 latestPrice = _ethprice; int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16; return ethValue; } // NOTE: Cannot draw a winner until collection is sold out function drawWinner() public onlyOwner soldOut{ uint256 tokenWinner = randomResult; int256 latestPrice = getLatestPrice(); int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16; address addressWinner = ownerOf(tokenWinner); (bool success, ) = payable(addressWinner).call{value: uint256(ethValue) }(""); require(success, "Transfer failed"); IS_DRAWN = true; winner = addressWinner; } // NOTE: Cannot withdraw until collection is sold out and winner has been paid function withdrawAll() public onlyOwner soldOut { require(IS_DRAWN, "Collection winner not drawn yet"); (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success, "Transfer failed"); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return "ipfs://QmVSymhzQAaY5FSEf8aVkKrTPYfXLzCYiUWq2woxsSmrvm"; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; contract RandomNumber is VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult = 10000; /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 */ constructor() VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10 ** 18; // 0.1 LINK (Varies by network) } /** * Requests randomness */ function getRandomNumber() public returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = (randomness % 10000) + 1; } // function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract Aggregator { AggregatorV3Interface internal priceFeed; /** * Network: Kovan * Aggregator: ETH/USD * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331 */ constructor() { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
NOTE: Cannot draw a winner until collection is sold out
function drawWinner() public onlyOwner soldOut{ uint256 tokenWinner = randomResult; int256 latestPrice = getLatestPrice(); int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16; address addressWinner = ownerOf(tokenWinner); require(success, "Transfer failed"); IS_DRAWN = true; winner = addressWinner; }
14,692,381
/** *Submitted for verification at Etherscan.io on 2022-03-24 */ /** *Submitted for verification at Etherscan.io on 2021-11-11 */ // SPDX-License-Identifier: UNLICENSED // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/SynthesisToken.sol pragma solidity 0.6.12; // SynthesisToken with Governance. contract SynthesisToken is ERC20("SynthesisToken", "SUSHI"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol //// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SynthesisSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SynthesisSwap must mint EXACTLY the same amount of SynthesisSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Synthesis. He can make Synthesis and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSynthesisPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSynthesisPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSynthesisPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The SUSHI TOKEN! SynthesisToken public synthesis; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public synthesisPerBlock; // Bonus muliplier for early synthesis makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SynthesisToken _synthesis, address _devaddr, uint256 _synthesisPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { synthesis = _synthesis; devaddr = _devaddr; synthesisPerBlock = _synthesisPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSynthesisPerShare: 0 })); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSynthesis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSynthesisPerShare = pool.accSynthesisPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 synthesisReward = multiplier.mul(synthesisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSynthesisPerShare = accSynthesisPerShare.add(synthesisReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSynthesisPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 synthesisReward = multiplier.mul(synthesisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); synthesis.mint(devaddr, synthesisReward.div(10)); synthesis.mint(address(this), synthesisReward); pool.accSynthesisPerShare = pool.accSynthesisPerShare.add(synthesisReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSynthesisPerShare).div(1e12).sub(user.rewardDebt); safeSynthesisTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSynthesisPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSynthesisPerShare).div(1e12).sub(user.rewardDebt); safeSynthesisTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSynthesisPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe synthesis transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSynthesisTransfer(address _to, uint256 _amount) internal { uint256 synthesisBal = synthesis.balanceOf(address(this)); if (_amount > synthesisBal) { synthesis.transfer(_to, synthesisBal); } else { synthesis.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSynthesisPerShare).div(1e12).sub(user.rewardDebt); safeSynthesisTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSynthesisPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
6,619,352
./full_match/97/0x5A4926C1DdcdF062aC4be7a84c83eB1AE4764336/sources/project_/contracts/Viddly.sol
Allows a user to join a video by paying the joining fee. Joins a video by paying the joining fee. videoId_ The ID of the video to join. referralAddress_ The referral address (optional). return True if the join operation is successful./
function joinVideo( string memory videoId_, address referralAddress_ ) external payable override returns (bool) { require(videos[videoId_].creator != address(0), "No such video exists"); require(msg.value >= _joiningFee, "Joining fee is less"); require(msg.sender!= referralAddress_,"new joiner address and referral address is not same"); require(!videoNodes[videoId_][msg.sender].exists,"You have already joined the video"); address[] memory Joiners = videos[videoId_].Joiners; for (uint i = 0; i < Joiners.length; i++) { require(Joiners[i] != referralAddress_, "Referral address is included in the new joiners"); } if (referralAddress_ == address(0)) { current = videos[videoId_].creator; current = referralAddress_; } while ( videoNodes[videoId_][current].left != address(0) && videoNodes[videoId_][current].right != address(0) ) { if ( _getBalance(videoId_, videoNodes[videoId_][current].left) < _getBalance(videoId_, videoNodes[videoId_][current].right) ) { current = videoNodes[videoId_][current].left; current = videoNodes[videoId_][current].right; } } if (endpointNode.left == address(0)) { endpointNode.left = msg.sender; endpointNode.right = msg.sender; } Node storage node = videoNodes[videoId_][msg.sender]; node.parent = current; node.exists = true; bool isFeeDistributed = _distributeFee(videoId_, msg.sender); require(isFeeDistributed, "Unable to distribute fee"); videos[videoId_].totalEarning += msg.value; emit VideoJoined(videoId_, msg.sender, msg.value); return true; }
3,276,058
//No Colored Allowed by DappVinci //The 'tokenURI' function returns SVG // SPDX-License-Identifier: MIT pragma solidity 0.7.0; contract Ownable { string public constant not_cur_owner108 = "018001"; //inject NONSTANDARD NAMING string public constant no_xfer_2_0983 = "018002"; //inject NONSTANDARD NAMING address public owner; event OWNERSHIPTRANSFERRED733(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING modifier ONLYOWNER618(){ //inject NONSTANDARD NAMING require(msg.sender == owner, not_cur_owner108); _; } function TRANSFEROWNERSHIP914(address _newOwner) public ONLYOWNER618 { //inject NONSTANDARD NAMING require(_newOwner != address(0), no_xfer_2_0983); emit OWNERSHIPTRANSFERRED733(owner, _newOwner); owner = _newOwner; }} library AddressUtils { function ISCONTRACT915(address _addr) internal view returns (bool addressCheck) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); }} interface ERC165{ function SUPPORTSINTERFACE217(bytes4 _interfaceID) external view returns (bool); //inject NONSTANDARD NAMING } contract SupportsInterface is ERC165 { mapping(bytes4 => bool) internal supportedInterfaces; function SUPPORTSINTERFACE217( //inject NONSTANDARD NAMING bytes4 _interfaceID) external override view returns (bool) { return supportedInterfaces[_interfaceID]; }} library SafeMath { string constant overflow201 = "008001"; //inject NONSTANDARD NAMING string constant subtrahend_greater_then_minuend467 = "008002"; //inject NONSTANDARD NAMING function ADD46(uint256 _addend1, uint256 _addend2) internal pure returns (uint256 sum) { //inject NONSTANDARD NAMING sum = _addend1 + _addend2; require(sum >= _addend1, overflow201); }} interface ERC721TokenReceiver { function ONERC721RECEIVED244(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4); //inject NONSTANDARD NAMING } interface ERC721{ event TRANSFER898(address indexed _from, address indexed _to, uint256 indexed _tokenId); //inject NONSTANDARD NAMING event APPROVAL562(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL444(address indexed _owner, address indexed _operator, bool _approved); //inject NONSTANDARD NAMING function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId, bytes calldata _data) external; //inject NONSTANDARD NAMING function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING function TRANSFERFROM921(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING function APPROVE958(address _approved, uint256 _tokenId) external; //inject NONSTANDARD NAMING function SETAPPROVALFORALL105(address _operator, bool _approved) external; //inject NONSTANDARD NAMING function BALANCEOF270(address _owner) external view returns (uint256); //inject NONSTANDARD NAMING function OWNEROF456(uint256 _tokenId) external view returns (address); //inject NONSTANDARD NAMING function GETAPPROVED790(uint256 _tokenId) external view returns (address); //inject NONSTANDARD NAMING function ISAPPROVEDFORALL873(address _owner, address _operator) external view returns (bool); //inject NONSTANDARD NAMING } contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; string constant zero_address727 = "003001"; //inject NONSTANDARD NAMING string constant not_valid_nft741 = "003002"; //inject NONSTANDARD NAMING string constant not_owner_or_operator13 = "003003"; //inject NONSTANDARD NAMING string constant not_owner_approwed_or_operator515 = "003004"; //inject NONSTANDARD NAMING string constant not_able_to_receive_nft141 = "003005"; //inject NONSTANDARD NAMING string constant nft_already_exists595 = "003006"; //inject NONSTANDARD NAMING string constant not_owner152 = "003007"; //inject NONSTANDARD NAMING string constant is_owner158 = "003008"; //inject NONSTANDARD NAMING bytes4 internal constant magic_on_erc721_received864 = 0x150b7a02; //inject NONSTANDARD NAMING mapping (uint256 => address) internal idToOwner; mapping (uint256 => address) internal idToApproval; mapping (address => uint256) private ownerToNFTokenCount; mapping (address => mapping (address => bool)) internal ownerToOperators; modifier CANOPERATE488(uint256 _tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], not_owner_or_operator13); _; } modifier CANTRANSFER713(uint256 _tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], not_owner_approwed_or_operator515); _; } modifier VALIDNFTOKEN826(uint256 _tokenId) { //inject NONSTANDARD NAMING require(idToOwner[_tokenId] != address(0), not_valid_nft741); _; } function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId, bytes calldata _data) external override{ //inject NONSTANDARD NAMING _SAFETRANSFERFROM261(_from, _to, _tokenId, _data); } function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId) external override { //inject NONSTANDARD NAMING _SAFETRANSFERFROM261(_from, _to, _tokenId, ""); } function TRANSFERFROM921(address _from, address _to, uint256 _tokenId) external override CANTRANSFER713(_tokenId) VALIDNFTOKEN826(_tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, not_owner152); require(_to != address(0), zero_address727); _TRANSFER192(_to, _tokenId); } function APPROVE958( address _approved, uint256 _tokenId) external override CANOPERATE488(_tokenId) VALIDNFTOKEN826(_tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, is_owner158); idToApproval[_tokenId] = _approved; emit APPROVAL562(tokenOwner, _approved, _tokenId); } function SETAPPROVALFORALL105(address _operator, bool _approved) external override { //inject NONSTANDARD NAMING ownerToOperators[msg.sender][_operator] = _approved; emit APPROVALFORALL444(msg.sender, _operator, _approved); } function BALANCEOF270(address _owner) external override view returns (uint256) { //inject NONSTANDARD NAMING require(_owner != address(0), zero_address727); return _GETOWNERNFTCOUNT378(_owner); } function OWNEROF456(uint256 _tokenId) external override view returns (address _owner){ //inject NONSTANDARD NAMING _owner = idToOwner[_tokenId]; require(_owner != address(0), not_valid_nft741); } function GETAPPROVED790(uint256 _tokenId) //inject NONSTANDARD NAMING external override view VALIDNFTOKEN826(_tokenId) returns (address) { return idToApproval[_tokenId]; } function ISAPPROVEDFORALL873(address _owner, address _operator) external override view returns (bool) { //inject NONSTANDARD NAMING return ownerToOperators[_owner][_operator]; } function _TRANSFER192(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING address from = idToOwner[_tokenId]; _CLEARAPPROVAL604(_tokenId); _REMOVENFTOKEN830(from, _tokenId); _ADDNFTOKEN970(_to, _tokenId); emit TRANSFER898(from, _to, _tokenId); } function _MINT19(address _to, uint256 _tokenId) internal virtual { //inject NONSTANDARD NAMING require(_to != address(0), zero_address727); require(idToOwner[_tokenId] == address(0), nft_already_exists595); _ADDNFTOKEN970(_to, _tokenId); emit TRANSFER898(address(0), _to, _tokenId); } function _REMOVENFTOKEN830(address _from, uint256 _tokenId) internal virtual { //inject NONSTANDARD NAMING require(idToOwner[_tokenId] == _from, not_owner152); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } function _ADDNFTOKEN970(address _to, uint256 _tokenId) internal virtual { //inject NONSTANDARD NAMING require(idToOwner[_tokenId] == address(0), nft_already_exists595); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].ADD46(1); } function _GETOWNERNFTCOUNT378(address _owner) internal virtual view returns (uint256){ //inject NONSTANDARD NAMING return ownerToNFTokenCount[_owner]; } function _SAFETRANSFERFROM261(address _from, address _to, uint256 _tokenId, bytes memory _data) //inject NONSTANDARD NAMING private CANTRANSFER713(_tokenId) VALIDNFTOKEN826(_tokenId){ address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, not_owner152); require(_to != address(0), zero_address727); _TRANSFER192(_to, _tokenId); if (_to.ISCONTRACT915()) { bytes4 retval = ERC721TokenReceiver(_to).ONERC721RECEIVED244(msg.sender, _from, _tokenId, _data); require(retval == magic_on_erc721_received864, not_able_to_receive_nft141); }} function _CLEARAPPROVAL604(uint256 _tokenId) private { //inject NONSTANDARD NAMING if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; }}} contract NFTokenMetadata is NFToken { string internal nftName; string internal nftSymbol; mapping (uint256 => string) internal idToUri; function NAME497() external view returns (string memory _name){ //inject NONSTANDARD NAMING _name = nftName; } function SYMBOL48() external view returns (string memory _symbol) { //inject NONSTANDARD NAMING _symbol = nftSymbol; }} contract NoColoredAllowed is NFTokenMetadata, Ownable{ constructor() { nftName = "No Colored Allowed"; nftSymbol = "XCA"; owner = msg.sender; supportedInterfaces[0x01ffc9a7] = true; // ERC165 supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } uint256 public artTotal; uint256 public artCap = 144; string public constant arthead473 = '<svg version="1.1" id="NoColoredAllowed" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1000 1000"><symbol id="a" viewBox="-7.9 -13 15.8 26"><path d="M2.6-12.7c0 6 .4-.3-5-.3-3 0-5.5 2-5.5 6.8 0 6.2 2.1 9.5 10.5 8.4 0 2.3.2 3.7-.5 4.8-.9 1.4-4.3 1.3-4.9-1.7h-5c.4 6.2 5.9 8.9 10.9 7.1 6.3-2.3 4.6-9 4.6-25.1H2.6zm0 10.9c-9.2 1.6-4.8-10.7-.7-5.9.9 1.2.7 2.8.7 5.9z"/></symbol><symbol id="b" viewBox="-7.7 -17.9 15.4 35.9"><path d="M-7.7-17.7v35.6h5.1c0-20.1-1.5-10 4.8-10C7.4 7.9 7.6 4 7.6-.5 7.6-10.3 9.1-18 2.3-18c-1.9 0-2.9.4-4.8 2.6-.1-3 .9-2.3-5.2-2.3zM2.5-.1c0 4.3-5 3.7-5 .2 0-10.6-.2-11 .7-12.1 1-1.2 3-1.1 3.8.1.7 1.3.5 2.5.5 11.8z"/></symbol><symbol id="c" viewBox="-7.6 -13 15.3 26"><path d="M-2.5-5.4c0-3.1 4.6-3.7 5 .1h5.1c0-8.6-11-10-14.2-4C-8.2-6.5-7.5 5.8-7.4 7c1.3 8.3 15 8.4 15-2.2H2.5c0 3.5-3.2 3.5-4.3 2.3-.9-.9-.7-1.2-.7-12.5z"/></symbol><symbol id="e" viewBox="-7.6 -13.1 15.3 26.1"><path d="M7.6-1.9C-4.5-1.9-2.5-.8-2.5-5.4c0-3.1 4.6-3.7 5 .1h5.1C7.6-15-7.6-16.7-7.6-4.2-7.6 5.2-8.4 9.4-4 12c4.4 2.6 11.7.5 11.7-6.9v-7zm-10.1 4c6.3 0 5-.9 5 2.9 0 2-1 2.9-2.5 2.9-2.9 0-2.5-2.9-2.5-5.8z"/></symbol><symbol id="f" viewBox="-5.8 -17.8 11.6 35.6"><path d="M-3.2-17.8c0 24.6 1 21.4-2.5 21.4 0 5-.8 4 2.5 4 0 8.5.9 10.2 8.9 10.2 0-6 .7-4.8-2.3-4.8-1.9 0-1.5-1.8-1.5-5.4 4.8 0 3.8 1 3.8-4-5.1 0-3.8 4.3-3.8-21.4h-5.1z"/></symbol><symbol id="h" viewBox="-7.7 -17.8 15.4 35.6"><path id="h_1_" d="M-7.7-17.8v35.6h5.1c0-20.5-1.6-10 4.9-10 6.6 0 5.2-5.9 5.2-25.6h-5C2.5 1 2.7.9 1.8 1.9.9 3.1-1.4 3-2 1.8-2.8.6-2.6 0-2.6-17.8h-5.1z"/></symbol><symbol id="i" viewBox="-2.7 -17.9 5.3 35.7"><path d="M-2.6 12.6c0 6.4-1.3 5.1 5.1 5.1.1-6.4 1.4-5.1-5.1-5.1zm0-30.5V7.5h5.1v-25.4h-5.1z"/></symbol><symbol id="m" viewBox="-12.7 -12.8 25.4 25.7"><path d="M-12.7-12.8v25.4h5.1c0-5.7-.5.3 4.9.3 1.5 0 3-.5 4.6-2.5 4.1 4.5 10.8 2.9 10.8-3.6v-19.5H7.6C7.6 6 7.8 5.8 7 6.9c-1 1.2-3.2 1-3.8-.1-.8-1.2-.7-1.3-.7-19.6h-5.1C-2.5 5.6-1.8 7.7-5 7.7c-3.4 0-2.5-2.1-2.5-20.5h-5.2z"/></symbol><symbol id="n" viewBox="-7.7 -12.8 15.4 25.6"><path d="M-7.7-12.8v25.4h5.1c0-5.7-.5.3 4.9.3 6.6 0 5.2-5.9 5.2-25.6h-5c0 18.7.2 18.5-.7 19.6-1 1.2-3.2 1-3.8-.1-.8-1.2-.6-1.8-.6-19.6h-5.1z"/></symbol><symbol id="o" viewBox="-7.8 -13.1 15.7 26.3"><path d="M7.7 4.1c0-8.8.9-13.5-3.5-16.1-4.1-2.5-10.6-.8-11.5 4.9-4.1 26.8 15 23 15 11.2zM-2.4-5.1c0-3.9 5-3.9 5 0 0 10.7.3 11.2-.6 12.2-.9 1-2.7 1-3.7 0-.9-1-.7-1.6-.7-12.2z"/></symbol><symbol id="p" viewBox="-7.7 -18 15.3 35.9"><path d="M-7.7-18v35.6h5.1c0-3.5-.5-2.3 2-.5 1.6 1.2 5.8 1.3 7.3-1.6 1.5-2.8.8-18.9.7-19.1C6.8-8.8.3-9.5-2.5-5.4c-.1 0-.1 1.1-.1-12.5h-5.1zM2.5 9.4c0 4.8-5 4.4-5 .3-.1-10.7-.3-10.8.7-11.8 1.1-1.2 3.1-1 3.8.1.7 1.2.5 1.3.5 11.4z"/></symbol><symbol id="r" viewBox="-6 -12.8 12 25.6"><path d="M-6-12.8v25.4h5.1c0-6-.2.3 6.8.3 0-8.3 1.1-4.1-3.3-5.4C-1.9 6.1-.9 2-.9-12.8H-6z"/></symbol><symbol id="s" viewBox="-7.7 -13 15.4 26"><path d="M2.4 5.6c-.1 3.5-5.1 3.4-5.1 0C-2.7 1.9 4 3 6.4-1.2 13-12.9-7.4-18.6-7.7-5.3c6.7 0 3.9.5 5.5-2s6.8.3 4.3 3.7c-.7 1-2.2 1.4-4.5 2.2C-8.7 1-8.7 7.7-5.3 11c4.2 4.2 12.5 1.9 12.5-5.4H2.4z"/></symbol><symbol id="t" viewBox="-5.5 -16.6 10.9 33.2"><path d="M-2.8 8.7c0 9.7-1.5 7.7 5.1 7.7 0-9.4-1-7.7 3.1-7.7 0-5 .8-4-3.1-4 0-15.5-.6-16.3 1.7-16.5 1.9-.2 1.4.9 1.4-4.9-10.5 0-8.2 4.6-8.2 21.4-3.3 0-2.5-1-2.5 4h2.5z"/></symbol><symbol id="u" viewBox="-7.7 -12.8 15.4 25.6"><path d="M7.7 12.8v-25.4H2.6c0 5.7.5-.3-4.9-.3-6.6 0-5.2 5.9-5.2 25.6h5.1C-2.5-6-2.7-5.8-1.8-6.9c.9-1.2 3.2-1 3.9.1.7 1.2.5 1.8.5 19.6h5.1z"/></symbol><symbol id="y" viewBox="-8.9 -17.8 17.7 35.7"><path d="M-8.9 17.8h5.4c4.7-21.1 2.5-21 7.1 0h5.2c-7.3-30-6.9-35.6-14.3-35.6-1.9 0-1.4-1-1.4 4.8 2.6 0 3.3-.1 4.2 3.1 1.2 4.3 1.6.6-6.2 27.7z"/></symbol><path id="bg" class="bg" d="M0 0h1000v1000H0z"/><g id="DV"><path id="V" d="M976.7 927.8c-16.6 66.5-9.9 66.8-26.6 0h26.6z"/><path id="D" d="M926.7 927.9c31.1-2 31.2 51.9 0 49.9v-49.9z"/></g><path id="hilite" d="M428.5 471h361.9v58H428.5z"/><path id="T" d="M199.7 442v-31.1c-7.3 0-5.8 1.3-5.8-4.9h16.6c0 6.1 1.5 4.9-5.8 4.9V442h-5z"/><use xlink:href="#h" width="15.4" height="35.6" x="-7.7" y="-17.8" transform="matrix(1 0 0 -1 221.781 423.8)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 242.106 428.925)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 262.83 428.775)"/><path id="k" d="M275.9 441.5v-35.6h5.1c0 22.9-.1 21.3.1 21.3 7.4-13.3 4.8-11.1 11.2-11.1l-6 10.3 7.3 15c-7 0-4.6 2.2-10.1-11-3.1 4.8-2.5 2.4-2.5 11h-5.1z"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 303.423 428.925)"/><use xlink:href="#f" width="11.6" height="35.6" x="-5.8" y="-17.8" transform="matrix(1 0 0 -1 330.453 423.8)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 346.17 428.925)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 365.228 428.775)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 392.42 428.925)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 412.376 429.075)"/><use xlink:href="#b" width="15.4" height="35.9" x="-7.7" y="-17.9" transform="matrix(1 0 0 -1 433.376 423.95)"/><use xlink:href="#m" width="25.4" height="25.7" x="-12.7" y="-12.8" transform="matrix(1 0 0 -1 459.15 428.775)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 479.836 423.8)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 491 425.075)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 503.9 425.075)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 516.1 423.8)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 532.024 428.775)"/><path id="g" d="M550.6 444.5c.2 3 5 3.8 5-.2 0-9.6.9-2.4-4.8-2.4-6.8 0-5.3-7.5-5.3-17.5 0-3.5-.2-6.2 2.5-7.8 1.1-.8 3.4-.8 4.5-.5 3.4 1 3.2 4.6 3.2.1h5.1v28.5c0 9.3-14 10.7-15.2-.1h5zm0-10.7c0 4.3 5 3.7 5 .2 0-10.7.2-11-.7-12.1-1-1.2-3-1.1-3.8.1-.8 1.3-.5 2.5-.5 11.8z"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 580.097 425.075)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 595.752 428.925)"/><path id="S" d="M636.8 416.1c-6.1 0-5.1.4-5.1-1.1 0-5.6-7-6.1-7 .3 0 8 10.7 3.2 12 12.6 2.4 18.5-17.3 18.2-17.3 3.6 6.1 0 5.1-.5 5.1 1.6 0 4.6 5.5 4.4 6.8 2.2.8-1.4.7-6.3 0-7.6-1.5-2.3-8.4-2.6-10.5-6.7-8-15.6 16-23 16-4.9z"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 649.37 429.075)"/><use xlink:href="#p" width="15.3" height="35.9" x="-7.7" y="-18" transform="matrix(1 0 0 -1 670.37 433.9)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 690.895 429.075)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 709.72 428.925)"/><path id="R" d="M719.9 441.5v-35.6h8.2c10.3 0 9.9 11.7 8 15.8-3.2 7.2-6.1-4.4 2.1 19.8-7.2 0-4.5 3-10.2-15.2-4.1 0-3-3-3 15.2h-5.1zm5.1-30.8c0 13.3-1 11.1 2.9 11.1 6.2 0 3.8-8.9 3.3-9.7-1.1-1.7-3.8-1.4-6.2-1.4z"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 749.444 428.925)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 768.87 428.775)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 785.144 429.065)"/><path id="dot" d="M797.8 441.5c0-6-1.2-4.8 4.8-4.8 0 6 1.2 4.8-4.8 4.8z"/><path id="U" d="M212.2 478c0 27.9 1.6 32.4-5.1 35.2-4.3 1.9-9-.4-10.8-4.4-.9-1.9-.6-.6-.6-30.8h5.1c0 28.7-1.1 30.8 3.2 30.8 4.2 0 3.1-2 3.1-30.8h5.1z"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 225.63 500.776)"/><use xlink:href="#f" width="11.6" height="35.6" x="-5.8" y="-17.8" transform="matrix(1 0 0 -1 242.555 495.95)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 258.204 500.925)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 276.73 500.776)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 290.454 497.076)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 307.788 501.075)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 328.228 500.776)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 348.253 501.075)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 363.903 497.18)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 379.653 500.925)"/><path id="l" d="M392 478h5.1c0 32.5-.9 30.7 2.5 31.1 0 5.2.8 5.3-3.2 4.5-5.8-1.2-4.4-4.6-4.4-35.6z"/><use xlink:href="#y" width="17.7" height="35.7" x="-8.9" y="-17.8" transform="matrix(1 0 0 -1 409.513 506.05)"/><g id="lit" fill="#fff"><path id="w" d="M456.9 488.3l-6 25.4h-4.5c-3-16.2-2.7-15-2.9-15-3.4 18.1-1.3 15-7.3 15l-6-25.4h5.4c3.4 17.1 3 15.8 3.2 15.8 3.4-18.9 1.5-15.8 6.8-15.8 3.7 21.4 1.9 20.6 5.8 0h5.5z"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 467.101 500.925)"/><use xlink:href="#c" width="15.3" height="26" x="-7.6" y="-13" transform="matrix(1 0 0 -1 498.15 500.925)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 516.95 500.925)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 537.6 500.776)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 558.074 500.776)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 578.299 501.012)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 593.748 497.076)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 619.847 501.012)"/><use xlink:href="#c" width="15.3" height="26" x="-7.6" y="-13" transform="matrix(1 0 0 -1 640.547 501.108)"/><use xlink:href="#c" width="15.3" height="26" x="-7.6" y="-13" transform="matrix(1 0 0 -1 660.297 500.925)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 679.195 501.108)"/><use xlink:href="#p" width="15.3" height="35.9" x="-7.7" y="-18" transform="matrix(1 0 0 -1 699.522 505.9)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 715.446 497.076)"/><use xlink:href="#y" width="17.7" height="35.7" x="-8.9" y="-17.8" transform="matrix(1 0 0 -1 741.295 506.05)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 760.148 500.925)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 780.458 501.075)"/></g><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 799.52 500.776)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 314.03 572.925)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 333.905 573.075)"/><use xlink:href="#b" width="15.4" height="35.9" x="-7.7" y="-17.9" transform="matrix(1 0 0 -1 354.704 567.95)"/><use xlink:href="#m" width="25.4" height="25.7" x="-12.7" y="-12.8" transform="matrix(1 0 0 -1 380.676 572.925)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 401.37 567.95)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 416.297 572.925)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 435.128 573.068)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 449.927 567.95)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 464.887 573.068)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 485.501 573.068)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 516.275 572.925)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 532.025 568.991)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 554.224 569.075)"/><use xlink:href="#h" width="15.4" height="35.6" x="-7.7" y="-17.8" transform="matrix(1 0 0 -1 570.548 567.8)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 586.268 567.8)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 601.073 572.925)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 626.822 569.075)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 638.072 567.8)"/><use xlink:href="#m" width="25.4" height="25.7" x="-12.7" y="-12.8" transform="matrix(1 0 0 -1 658.871 572.776)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 684.273 572.863)"/><style>.bg{fill:#'; //inject NONSTANDARD NAMING string public constant arttail672 = ';}</style></svg>'; //inject NONSTANDARD NAMING mapping (uint256 => string) internal artDNAStore; mapping (uint256 => uint256) internal artSetStore; event BIRTH139(uint256 tokenID, string artDNA, uint256 artSet); //inject NONSTANDARD NAMING function GETDNA928(uint256 tokenID) public view returns (string memory artDNA) { //inject NONSTANDARD NAMING artDNA = artDNAStore[tokenID]; } function GETSET947(uint256 tokenID) public view returns (uint256 artSet) { //inject NONSTANDARD NAMING artSet = artSetStore[tokenID]; } function GENERATE93(uint256 tokenID) public view returns (string memory SVG) { //inject NONSTANDARD NAMING SVG = string(abi.encodePacked(arthead473, artDNAStore[tokenID], arttail672)); } function TOKENURI670(uint256 _tokenId) external view VALIDNFTOKEN826(_tokenId) returns (string memory) { //inject NONSTANDARD NAMING return GENERATE93(_tokenId); } function TOKENIZE443 (string memory artDNA, uint256 artSet) public ONLYOWNER618 {{ //inject NONSTANDARD NAMING artTotal = artTotal + 1; artDNAStore[artTotal] = artDNA; artSetStore[artTotal] = artSet; _MINTPRINT97(); emit BIRTH139(artTotal, artDNA, artSet); }} function _MINTPRINT97() private { //inject NONSTANDARD NAMING uint256 tokenId = artTotal; require(artTotal <= artCap, "144 tokens max"); _MINT19(msg.sender, tokenId); }}
inject NONSTANDARD NAMING
function GETAPPROVED790(uint256 _tokenId) external view returns (address);
15,841,675
./partial_match/1/0x8a3C710E41cD95799C535f22DBaE371D7C858651/sources/Xccelerate.sol
internal function cannot mint after deployment
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } constructor() ERC20("Xccelerate", "XLRT") { _mint(msg.sender, _totalSupply); }
9,232,321
./partial_match/1/0x84Bb947fcEdba6B9C7DCEad42dF07e113bb03007/sources/StaterToken.sol
Returns the cap on the token's total supply./
function cap() public view returns (uint256) { return _cap; }
3,656,256
./partial_match/1/0xd9b7eC74C06c558A59AfdE6a16E614950730F44d/sources/contracts/engine/V3/GenArt721CoreV3_Engine_Flex.sol
Updates randomizer address to `_randomizerAddress`. _randomizerAddress New randomizer address. Note that this method does not check that the input address is not `address(0)`, as it is expected that callers of this method should perform input validation where applicable./ populate historical randomizer array
function _updateRandomizerAddress(address _randomizerAddress) internal { randomizerContract = IRandomizer_V3CoreBase(_randomizerAddress); _historicalRandomizerAddresses.push(_randomizerAddress); emit PlatformUpdated(FIELD_RANDOMIZER_ADDRESS); }
3,903,945
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_543(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,256
pragma solidity ^0.8.0; // 可用在地址型变量的工具库 library Address { // 检查目标地址是否一个合约 // internal 限制了这个函数只能由 import 这个合约的合约内部来使用 // view 声明了这个函数不会修改状态 function isContract(address addr) internal view returns (bool) { uint256 size; // 通过判断地址所关联的代码大小来判断某个地址上是否有一个合约 // assembly 指明了后边的程序是内联汇编的 assembly { // 用 extcodesize 函数取得输入参数 addr 所对应的账户地址关联的 EVM 字节码数据的长度 size := extcodesize(addr) } return size > 0; } // 是否为空地址 function isEmptyAddress(address addr) internal pure returns (bool) { return addr == address(0); } // 地址转换为字节 function addressToBytes(address addr) internal pure returns (bytes memory) { bytes20 addrBytes = bytes20(uint160(addr)); bytes memory rtn = new bytes(20); for (uint8 i = 0; i < 20; i++) { rtn[i] = addrBytes[i]; } return rtn; } // 字节转换为地址 function bytesToAddress(bytes memory addrBytes) internal pure returns (address) { require(addrBytes.length == 20); uint160 intVal = 0; for (uint8 i = 0; i < 20; i++) { intVal <<= 8; intVal += uint8(addrBytes[i]); } return address(intVal); } // 发送值,需要判断该地址下的越是否大于 amount function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } // 将数字 0-15 转为为 ASCII 值 [0-9 A-F a-f] function encode(uint8 num) private pure returns (byte) { if (num >= 0 && num <= 9) { return byte(num + 48); } return byte(num + 87); } // 将 ASCII 值 [0-9 A-F a-f] 转为为 数字 0-15 function decode(byte asc) private pure returns (uint8) { uint8 val = uint8(asc); // 如果是 0-9 if (val >= 48 && val <= 57) { return val - 48; } // 如果是 A-F if (val >= 65 && val <= 70) { return val - 55; } // 否则是 a-f return val - 87; } }
将数字 0-15 转为为 ASCII 值 [0-9 A-F a-f]
function encode(uint8 num) private pure returns (byte) { if (num >= 0 && num <= 9) { return byte(num + 48); } return byte(num + 87); }
1,065,927
// SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.8.0; import {AddressIsContract} from "@animoca/ethereum-contracts-core/contracts/utils/types/AddressIsContract.sol"; import {ERC1155InventoryIdentifiersLib} from "./../ERC1155/ERC1155InventoryIdentifiersLib.sol"; import {IERC165} from "@animoca/ethereum-contracts-core/contracts/introspection/IERC165.sol"; import {IERC721} from "./../ERC721/interfaces/IERC721.sol"; import {IERC721Metadata} from "./../ERC721/interfaces/IERC721Metadata.sol"; import {IERC721BatchTransfer} from "./../ERC721/interfaces/IERC721BatchTransfer.sol"; import {IERC721Receiver} from "./../ERC721/interfaces/IERC721Receiver.sol"; import {IERC1155MetadataURI} from "./../ERC1155/interfaces/IERC1155MetadataURI.sol"; import {IERC1155TokenReceiver} from "./../ERC1155/interfaces/IERC1155TokenReceiver.sol"; import {IERC1155Inventory} from "./../ERC1155/interfaces/IERC1155Inventory.sol"; import {IERC1155721Inventory} from "./interfaces/IERC1155721Inventory.sol"; import {ERC1155InventoryBase} from "./../ERC1155/ERC1155InventoryBase.sol"; /** * @title ERC1155721Inventory, an ERC1155Inventory with additional support for ERC721. * @dev The function `uri(uint256)` needs to be implemented by a child contract, for example with the help of `NFTBaseMetadataURI`. */ abstract contract ERC1155721Inventory is IERC1155721Inventory, IERC721Metadata, ERC1155InventoryBase { using ERC1155InventoryIdentifiersLib for uint256; using AddressIsContract for address; uint256 internal constant _APPROVAL_BIT_TOKEN_OWNER_ = 1 << 160; string internal _name; string internal _symbol; /* owner => NFT balance */ mapping(address => uint256) internal _nftBalances; /* NFT ID => operator */ mapping(uint256 => address) internal _nftApprovals; constructor( string memory name_, string memory symbol_, uint256 collectionMaskLength ) ERC1155InventoryBase(collectionMaskLength) { _name = name_; _symbol = symbol_; } //======================================================= ERC165 ========================================================// /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721BatchTransfer).interfaceId || super.supportsInterface(interfaceId); } //=================================================== ERC721Metadata ====================================================// /// @inheritdoc IERC721Metadata function name() public view virtual override returns (string memory) { return _name; } /// @inheritdoc IERC721Metadata function symbol() public view virtual override returns (string memory) { return _symbol; } /// @inheritdoc IERC721Metadata function tokenURI(uint256 nftId) external view virtual override returns (string memory) { require(address(uint160(_owners[nftId])) != address(0), "Inventory: non-existing NFT"); return uri(nftId); } //================================================= ERC1155MetadataURI ==================================================// /// @inheritdoc IERC1155MetadataURI function uri(uint256) public view virtual override returns (string memory); //======================================================= ERC721 ========================================================// /// @inheritdoc IERC721 function balanceOf(address tokenOwner) external view virtual override returns (uint256) { require(tokenOwner != address(0), "Inventory: zero address"); return _nftBalances[tokenOwner]; } /// @inheritdoc IERC721 function approve(address to, uint256 tokenId) public virtual override { uint256 owner = _owners[tokenId]; require(owner != 0, "Inventory: non-existing NFT"); address ownerAddress = address(uint160(owner)); require(to != ownerAddress, "Inventory: self-approval"); require(_isOperatable(ownerAddress, _msgSender()), "Inventory: non-approved sender"); if (to == address(0)) { if (owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) { // remove the approval bit if it is present _owners[tokenId] = uint256(ownerAddress); } } else { uint256 ownerWithApprovalBit = owner | _APPROVAL_BIT_TOKEN_OWNER_; if (owner != ownerWithApprovalBit) { // add the approval bit if it is not present _owners[tokenId] = ownerWithApprovalBit; } _nftApprovals[tokenId] = to; } emit Approval(ownerAddress, to, tokenId); } /// @inheritdoc IERC721 function getApproved(uint256 tokenId) public view virtual override returns (address) { uint256 owner = _owners[tokenId]; require(address(uint160(owner)) != address(0), "Inventory: non-existing NFT"); if (owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) { return _nftApprovals[tokenId]; } else { return address(0); } } /// @inheritdoc IERC1155721Inventory function transferFrom( address from, address to, uint256 nftId ) public virtual override { _transferFrom( from, to, nftId, "", /* safe */ false ); } /// @inheritdoc IERC1155721Inventory function safeTransferFrom( address from, address to, uint256 nftId ) public virtual override { _transferFrom( from, to, nftId, "", /* safe */ true ); } /// @inheritdoc IERC1155721Inventory function safeTransferFrom( address from, address to, uint256 nftId, bytes memory data ) public virtual override { _transferFrom( from, to, nftId, data, /* safe */ true ); } /// @inheritdoc IERC1155721Inventory function batchTransferFrom( address from, address to, uint256[] memory nftIds ) public virtual override { require(to != address(0), "Inventory: transfer to zero"); address sender = _msgSender(); bool operatable = _isOperatable(from, sender); uint256 length = nftIds.length; uint256[] memory values = new uint256[](length); uint256 nfCollectionId; uint256 nfCollectionCount; for (uint256 i; i != length; ++i) { uint256 nftId = nftIds[i]; values[i] = 1; _transferNFT(from, to, nftId, 1, operatable, true); emit Transfer(from, to, nftId); uint256 nextCollectionId = nftId.getNonFungibleCollection(_collectionMaskLength); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount); nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } if (nfCollectionId != 0) { _transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount); _transferNFTUpdateBalances(from, to, length); } emit TransferBatch(_msgSender(), from, to, nftIds, values); if (to.isContract() && _isERC1155TokenReceiver(to)) { _callOnERC1155BatchReceived(from, to, nftIds, values, ""); } } //======================================================= ERC1155 =======================================================// /// @inheritdoc IERC1155721Inventory function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes memory data ) public virtual override(IERC1155Inventory, IERC1155721Inventory) { address sender = _msgSender(); require(to != address(0), "Inventory: transfer to zero"); bool operatable = _isOperatable(from, sender); if (id.isFungibleToken()) { _transferFungible(from, to, id, value, operatable); } else if (id.isNonFungibleToken(_collectionMaskLength)) { _transferNFT(from, to, id, value, operatable, false); emit Transfer(from, to, id); } else { revert("Inventory: not a token id"); } emit TransferSingle(sender, from, to, id, value); if (to.isContract()) { _callOnERC1155Received(from, to, id, value, data); } } /// @inheritdoc IERC1155721Inventory function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) public virtual override(IERC1155Inventory, IERC1155721Inventory) { _safeBatchTransferFrom(from, to, ids, values, data); } //================================================== ERC721 && ERC1155 ==================================================// /// @inheritdoc IERC1155721Inventory function setApprovalForAll(address operator, bool approved) public virtual override(IERC1155721Inventory, ERC1155InventoryBase) { super.setApprovalForAll(operator, approved); } /// @inheritdoc IERC1155721Inventory function isApprovedForAll(address tokenOwner, address operator) public view virtual override(IERC1155721Inventory, ERC1155InventoryBase) returns (bool) { return super.isApprovedForAll(tokenOwner, operator); } //============================================== ERC721 && ERC1155Inventory ===============================================// /// @inheritdoc IERC1155721Inventory function ownerOf(uint256 nftId) public view virtual override(IERC1155721Inventory, ERC1155InventoryBase) returns (address) { return super.ownerOf(nftId); } //============================================ High-level Internal Functions ============================================// /** * Safely or unsafely transfers some token (ERC721-compatible). * @dev For `safe` transfer, see {IERC1155721Inventory-transferFrom(address,address,uint256)}. * @dev For un`safe` transfer, see {IERC1155721Inventory-safeTransferFrom(address,address,uint256,bytes)}. */ function _transferFrom( address from, address to, uint256 nftId, bytes memory data, bool safe ) internal { require(to != address(0), "Inventory: transfer to zero"); address sender = _msgSender(); bool operatable = _isOperatable(from, sender); _transferNFT(from, to, nftId, 1, operatable, false); emit Transfer(from, to, nftId); emit TransferSingle(sender, from, to, nftId, 1); if (to.isContract()) { if (_isERC1155TokenReceiver(to)) { _callOnERC1155Received(from, to, nftId, 1, data); } else if (safe) { _callOnERC721Received(from, to, nftId, data); } } } /** * Safely transfers a batch of tokens (ERC1155-compatible). * @dev See {IERC1155721Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { require(to != address(0), "Inventory: transfer to zero"); uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); address sender = _msgSender(); bool operatable = _isOperatable(from, sender); uint256 nfCollectionId; uint256 nfCollectionCount; uint256 nftsCount; for (uint256 i; i != length; ++i) { uint256 id = ids[i]; if (id.isFungibleToken()) { _transferFungible(from, to, id, values[i], operatable); } else if (id.isNonFungibleToken(_collectionMaskLength)) { _transferNFT(from, to, id, values[i], operatable, true); emit Transfer(from, to, id); uint256 nextCollectionId = id.getNonFungibleCollection(_collectionMaskLength); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount); nfCollectionId = nextCollectionId; nftsCount += nfCollectionCount; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } else { revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { _transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount); nftsCount += nfCollectionCount; _transferNFTUpdateBalances(from, to, nftsCount); } emit TransferBatch(_msgSender(), from, to, ids, values); if (to.isContract()) { _callOnERC1155BatchReceived(from, to, ids, values, data); } } /** * Safely or unsafely mints some token (ERC721-compatible). * @dev For `safe` mint, see {IERC1155721InventoryMintable-mint(address,uint256)}. * @dev For un`safe` mint, see {IERC1155721InventoryMintable-safeMint(address,uint256,bytes)}. */ function _mint( address to, uint256 nftId, bytes memory data, bool safe ) internal { require(to != address(0), "Inventory: mint to zero"); require(nftId.isNonFungibleToken(_collectionMaskLength), "Inventory: not an NFT"); _mintNFT(to, nftId, 1, false); emit Transfer(address(0), to, nftId); emit TransferSingle(_msgSender(), address(0), to, nftId, 1); if (to.isContract()) { if (_isERC1155TokenReceiver(to)) { _callOnERC1155Received(address(0), to, nftId, 1, data); } else if (safe) { _callOnERC721Received(address(0), to, nftId, data); } } } /** * Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible). * @dev See {IERC1155721InventoryMintable-batchMint(address,uint256[])}. */ function _batchMint(address to, uint256[] memory nftIds) internal { require(to != address(0), "Inventory: mint to zero"); uint256 length = nftIds.length; uint256[] memory values = new uint256[](length); uint256 nfCollectionId; uint256 nfCollectionCount; for (uint256 i; i != length; ++i) { uint256 nftId = nftIds[i]; require(nftId.isNonFungibleToken(_collectionMaskLength), "Inventory: not an NFT"); values[i] = 1; _mintNFT(to, nftId, 1, true); emit Transfer(address(0), to, nftId); uint256 nextCollectionId = nftId.getNonFungibleCollection(_collectionMaskLength); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; _nftBalances[to] += length; emit TransferBatch(_msgSender(), address(0), to, nftIds, values); if (to.isContract() && _isERC1155TokenReceiver(to)) { _callOnERC1155BatchReceived(address(0), to, nftIds, values, ""); } } /** * Safely mints some token (ERC1155-compatible). * @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}. */ function _safeMint( address to, uint256 id, uint256 value, bytes memory data ) internal virtual { require(to != address(0), "Inventory: mint to zero"); address sender = _msgSender(); if (id.isFungibleToken()) { _mintFungible(to, id, value); } else if (id.isNonFungibleToken(_collectionMaskLength)) { _mintNFT(to, id, value, false); emit Transfer(address(0), to, id); } else { revert("Inventory: not a token id"); } emit TransferSingle(sender, address(0), to, id, value); if (to.isContract()) { _callOnERC1155Received(address(0), to, id, value, data); } } /** * Safely mints a batch of tokens (ERC1155-compatible). * @dev See {IERC1155721InventoryMintable-safeBatchMint(address,uint256[],uint256[],bytes)}. */ function _safeBatchMint( address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal virtual { require(to != address(0), "Inventory: mint to zero"); uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); uint256 nfCollectionId; uint256 nfCollectionCount; uint256 nftsCount; for (uint256 i; i != length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (id.isFungibleToken()) { _mintFungible(to, id, value); } else if (id.isNonFungibleToken(_collectionMaskLength)) { _mintNFT(to, id, value, true); emit Transfer(address(0), to, id); uint256 nextCollectionId = id.getNonFungibleCollection(_collectionMaskLength); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; nfCollectionId = nextCollectionId; nftsCount += nfCollectionCount; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } else { revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; nftsCount += nfCollectionCount; _nftBalances[to] += nftsCount; } emit TransferBatch(_msgSender(), address(0), to, ids, values); if (to.isContract()) { _callOnERC1155BatchReceived(address(0), to, ids, values, data); } } /** * Safely mints some tokens to a list of recipients. * @dev See {IERC1155721Deliverable-safeDeliver(address[],uint256[],uint256[],bytes)}. */ function _safeDeliver( address[] calldata recipients, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) internal { uint256 length = recipients.length; require(length == ids.length && length == values.length, "Inventory: inconsistent arrays"); address sender = _msgSender(); for (uint256 i; i != length; ++i) { address to = recipients[i]; require(to != address(0), "Inventory: mint to zero"); uint256 id = ids[i]; uint256 value = values[i]; if (id.isFungibleToken()) { _mintFungible(to, id, value); emit TransferSingle(sender, address(0), to, id, value); if (to.isContract()) { _callOnERC1155Received(address(0), to, id, value, data); } } else if (id.isNonFungibleToken(_collectionMaskLength)) { _mintNFT(to, id, value, false); emit Transfer(address(0), to, id); emit TransferSingle(sender, address(0), to, id, 1); if (to.isContract()) { if (_isERC1155TokenReceiver(to)) { _callOnERC1155Received(address(0), to, id, 1, data); } else { _callOnERC721Received(address(0), to, id, data); } } } else { revert("Inventory: not a token id"); } } } //============================================== Helper Internal Functions ==============================================// function _mintFungible( address to, uint256 id, uint256 value ) internal { require(value != 0, "Inventory: zero value"); uint256 supply = _supplies[id]; uint256 newSupply = supply + value; require(newSupply > supply, "Inventory: supply overflow"); _supplies[id] = newSupply; // cannot overflow as supply cannot overflow _balances[id][to] += value; } function _mintNFT( address to, uint256 id, uint256 value, bool isBatch ) internal { require(value == 1, "Inventory: wrong NFT value"); require(_owners[id] == 0, "Inventory: existing/burnt NFT"); _owners[id] = uint256(uint160(to)); if (!isBatch) { uint256 collectionId = id.getNonFungibleCollection(_collectionMaskLength); // it is virtually impossible that a Non-Fungible Collection supply // overflows due to the cost of minting individual tokens ++_supplies[collectionId]; ++_balances[collectionId][to]; ++_nftBalances[to]; } } function _transferFungible( address from, address to, uint256 id, uint256 value, bool operatable ) internal { require(operatable, "Inventory: non-approved sender"); require(value != 0, "Inventory: zero value"); uint256 balance = _balances[id][from]; require(balance >= value, "Inventory: not enough balance"); if (from != to) { _balances[id][from] = balance - value; // cannot overflow as supply cannot overflow _balances[id][to] += value; } } function _transferNFT( address from, address to, uint256 id, uint256 value, bool operatable, bool isBatch ) internal virtual { require(value == 1, "Inventory: wrong NFT value"); uint256 owner = _owners[id]; require(from == address(uint160(owner)), "Inventory: non-owned NFT"); if (!operatable) { require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[id], "Inventory: non-approved sender"); } _owners[id] = uint256(uint160(to)); if (!isBatch) { _transferNFTUpdateBalances(from, to, 1); _transferNFTUpdateCollection(from, to, id.getNonFungibleCollection(_collectionMaskLength), 1); } } function _transferNFTUpdateBalances( address from, address to, uint256 amount ) internal virtual { if (from != to) { // cannot underflow as balance is verified through ownership _nftBalances[from] -= amount; // cannot overflow as supply cannot overflow _nftBalances[to] += amount; } } function _transferNFTUpdateCollection( address from, address to, uint256 collectionId, uint256 amount ) internal virtual { if (from != to) { // cannot underflow as balance is verified through ownership _balances[collectionId][from] -= amount; // cannot overflow as supply cannot overflow _balances[collectionId][to] += amount; } } /** * Queries whether a contract implements ERC1155TokenReceiver. * @param _contract address of the contract. * @return wheter the given contract implements ERC1155TokenReceiver. */ function _isERC1155TokenReceiver(address _contract) internal view returns (bool) { bool success; bool result; bytes memory staticCallData = abi.encodeWithSelector(type(IERC165).interfaceId, type(IERC1155TokenReceiver).interfaceId); assembly { let call_ptr := add(0x20, staticCallData) let call_size := mload(staticCallData) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall(10000, _contract, call_ptr, call_size, output, 0x20) // 32 bytes result := mload(output) } // (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas assert(gasleft() > 158); return success && result; } /** * Calls {IERC721Receiver-onERC721Received} on a target contract. * @dev Reverts if `to` is not a contract. * @dev Reverts if the call to the target fails or is refused. * @param from Previous token owner. * @param to New token owner. * @param nftId Identifier of the token transferred. * @param data Optional data to send along with the receiver contract call. */ function _callOnERC721Received( address from, address to, uint256 nftId, bytes memory data ) internal { require( IERC721Receiver(to).onERC721Received(_msgSender(), from, nftId, data) == type(IERC721Receiver).interfaceId, "Inventory: transfer refused" ); } }
@inheritdoc IERC1155MetadataURI======================================================= ERC721 ======================================================== @inheritdoc IERC721
function uri(uint256) public view virtual override returns (string memory); function balanceOf(address tokenOwner) external view virtual override returns (uint256) { require(tokenOwner != address(0), "Inventory: zero address"); return _nftBalances[tokenOwner]; }
1,078,450
./full_match/4/0xbc4F1d7BeB7f156bF2e3541AC8535364E0F3C279/sources/ERC721radableV7.sol
Mints `tokenId` and transfers it to `to`. WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible Requirements: - `tokenId` must not exist. - `to` cannot be the zero address. Emits a {Transfer} event./
function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; totalSupply_ += 1; emit Transfer(address(0), to, tokenId); }
802,238
./full_match/80001/0x07f9E0dB59080a9632609979064E76328c340E0d/sources/contracts/OnlineShop.sol
Get Transaction By BuyerSet Product Details
function getTransactionByBuyer (address userAddr) public view returns(SalesTransaction.SalesTransactionView[] memory) { uint transactionCount = _transactionId.current(); uint currentIndex = 0; uint numOfItem = 0; for (uint i = 0; i < transactionCount; i++) { if (idToSalesTransactionMap[i + 1].buyer() == userAddr) { numOfItem +=1; } } SalesTransaction.SalesTransactionView[] memory salesTransactionList = new SalesTransaction.SalesTransactionView[](numOfItem); for (uint i = 0; i < transactionCount; i++) { if (idToSalesTransactionMap[i + 1].buyer() == userAddr) { salesTransactionList[currentIndex] = idToSalesTransactionMap[i + 1].toViewObject(); salesTransactionList[currentIndex].transactionId = i + 1; ProductItem memory product = idToProductItemMap[salesTransactionList[currentIndex].salesProductId]; salesTransactionList[currentIndex].title = product.title; salesTransactionList[currentIndex].desp = product.desp; salesTransactionList[currentIndex].productImage = product.productImage; salesTransactionList[currentIndex].sellerPublicKey = product.sellerPublicKey; currentIndex +=1; } } return salesTransactionList; }
5,597,278
./partial_match/1/0x5D2A8C81f349D93f814acC9Aa3D3D62f54F7A19D/sources/AmbrosusSale.sol
Called once by anybody after the sale ends. Initialises the specific values (i.e. absolute token quantities) of the allowed liquid/locked allocations. Preconditions: !allocations_initialised Postconditions: allocations_initialised, !allocations_complete Writes {Allocations}
function initialiseAllocations() public only_after_sale when_allocations_uninitialised { allocationsInitialised = true; liquidAllocatable = LIQUID_ALLOCATION_PPM * totalSold / SALES_ALLOCATION_PPM; lockedAllocatable = LOCKED_ALLOCATION_PPM * totalSold / SALES_ALLOCATION_PPM; }
3,930,278