file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/1/0xf4BC293A38bD1E3875Cfc141Ba81dd8E95F65f90/sources/StrategyConic.sol
Adds liquidity to AMM and gets more LP tokens.
function _addLiquidity() internal { uint nativeBal = _balanceOfThis(native); if (nativeToUnderlyingPath.length > 0) { UniswapV3Utils.swap(unirouter, nativeToUnderlyingPath, nativeBal); ICurveRouter(curveRouter).exchange_multiple(nativeToUnderlying.route, nativeToUnderlying.swapParams, nativeBal, 0); } uint bal = _balanceOfThis(underlying); if (bal > 0) { IConicPool(conicPool).deposit(bal, 0, false); } }
4,260,140
./full_match/1/0xe261B138cfd46FdC12A039cF6690645f35DCFA37/sources/contracts/Global/AuthorityModel.sol
____________________________________________________________________________________________________________________ -->GETTER (function) isSuperAdmin check if an address is the super admin --------------------------------------------------------------------------------------------------------------------- return bool --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/
function isSuperAdmin(address queryAddress_) public view returns (bool) { return (superAdmin == queryAddress_); }
3,107,381
pragma solidity ^0.5.16; import "./VToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/XVS.sol"; import "./VAI/VAI.sol"; /** * @title Venus's Comptroller Contract * @author Venus */ contract Comptroller is ComptrollerV4Storage, ComptrollerInterfaceG2, ComptrollerErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(VToken vToken); /// @notice Emitted when an account enters a market event MarketEntered(VToken vToken, address account); /// @notice Emitted when an account exits a market event MarketExited(VToken vToken, 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(VToken vToken, 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 VAI Vault info is changed event NewVAIVaultInfo(address vault_, uint releaseStartBlock_, uint releaseInterval_); /// @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(VToken vToken, string action, bool pauseState); /// @notice Emitted when Venus VAI rate is changed event NewVenusVAIRate(uint oldVenusVAIRate, uint newVenusVAIRate); /// @notice Emitted when Venus VAI Vault rate is changed event NewVenusVAIVaultRate(uint oldVenusVAIVaultRate, uint newVenusVAIVaultRate); /// @notice Emitted when a new Venus speed is calculated for a market event VenusSpeedUpdated(VToken indexed vToken, uint newSpeed); /// @notice Emitted when XVS is distributed to a supplier event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex); /// @notice Emitted when XVS is distributed to a borrower event DistributedBorrowerVenus(VToken indexed vToken, address indexed borrower, uint venusDelta, uint venusBorrowIndex); /// @notice Emitted when XVS is distributed to a VAI minter event DistributedVAIMinterVenus(address indexed vaiMinter, uint venusDelta, uint venusVAIMintIndex); /// @notice Emitted when XVS is distributed to VAI Vault event DistributedVAIVaultVenus(uint amount); /// @notice Emitted when VAIController is changed event NewVAIController(VAIControllerInterface oldVAIController, VAIControllerInterface newVAIController); /// @notice Emitted when VAI mint rate is changed by admin event NewVAIMintRate(uint oldVAIMintRate, uint newVAIMintRate); /// @notice Emitted when protocol state is changed by admin event ActionProtocolPaused(bool state); /// @notice Emitted when borrow cap for a vToken is changed event NewBorrowCap(VToken indexed vToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when treasury guardian is changed event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian); /// @notice Emitted when treasury address is changed event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress); /// @notice Emitted when treasury percent is changed event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent); /// @notice The initial Venus index for a market uint224 public constant venusInitialIndex = 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 constructor() public { admin = msg.sender; } modifier onlyProtocolAllowed { require(!protocolPaused, "protocol is paused"); _; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } modifier onlyListedMarket(VToken vToken) { require(markets[address(vToken)].isListed, "venus market is not listed"); _; } modifier validPauseState(bool state) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can"); require(msg.sender == admin || state == true, "only admin can unpause"); _; } /*** 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 (VToken[] memory) { return accountAssets[account]; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param vToken The vToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, VToken vToken) external view returns (bool) { return markets[address(vToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param vTokens The list of addresses of the vToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) { uint len = vTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param vToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { // 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(vToken); emit MarketEntered(vToken, 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 vTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the vToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); require(oErr == 0, "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(vTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set vToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete vToken from the account’s list of assets */ // In order to delete vToken, copy last item in list to location of item to be removed, reduce length by 1 VToken[] storage userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(i < len); emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param vToken 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 vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[vToken], "mint is paused"); // Shh - currently unused mintAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, minter); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param vToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address vToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused vToken; minter; actualMintAmount; mintTokens; } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param vToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of vTokens 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 vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) { uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, VToken(vToken), 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 vToken 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 vToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused vToken; redeemer; // Require tokens is zero or amount is also zero require(redeemTokens != 0 || redeemAmount == 0, "redeemTokens zero"); } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param vToken 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 vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { // only vTokens may call borrowAllowed if borrower not in market require(msg.sender == vToken, "sender must be vToken"); // attempt to add borrower to the market Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[vToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = VToken(vToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 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: VToken(vToken).borrowIndex()}); updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param vToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address vToken, address borrower, uint borrowAmount) external { // Shh - currently unused vToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param vToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would repay 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 vToken, address payer, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param vToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address vToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused vToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param vTokenBorrowed Asset which was borrowed by the borrower * @param vTokenCollateral 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 vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { // Shh - currently unused liquidator; if (!(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController)) || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(0), 0, 0); 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; if (address(vTokenBorrowed) != address(vaiController)) { borrowBalance = VToken(vTokenBorrowed).borrowBalanceStored(borrower); } else { borrowBalance = mintedVAIs[borrower]; } uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param vTokenBorrowed Asset which was borrowed by the borrower * @param vTokenCollateral 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 actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused vTokenBorrowed; vTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param vTokenCollateral Asset which was used as collateral and will be seized * @param vTokenBorrowed 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 vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; // We've added VAIController as a borrowed token list check for seize if (!markets[vTokenCollateral].isListed || !(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController))) { return uint(Error.MARKET_NOT_LISTED); } if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateVenusSupplyIndex(vTokenCollateral); distributeSupplierVenus(vTokenCollateral, borrower); distributeSupplierVenus(vTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param vTokenCollateral Asset which was used as collateral and will be seized * @param vTokenBorrowed 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 seizeVerify( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused vTokenCollateral; vTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param vToken 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 vTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed 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(vToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, src); distributeSupplierVenus(vToken, dst); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param vToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of vTokens to transfer */ function transferVerify(address vToken, address src, address dst, uint transferTokens) external { // Shh - currently unused vToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `vTokenBalance` is the number of vTokens 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 vTokenBalance; 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, VToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param vTokenModify 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 vTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(vTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param vTokenModify 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 vToken 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, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; // Read the balances and exchange rate from the vToken (oErr, vars.vTokenBalance, 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 -> bnb (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * vTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with vTokenModify if (asset == vTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } vars.sumBorrowPlusEffects = add_(vars.sumBorrowPlusEffects, mintedVAIs[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 Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in vToken.liquidateBorrowFresh) * @param vTokenBorrowed The address of the borrowed vToken * @param vTokenCollateral The address of the collateral vToken * @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens * @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address vTokenBorrowed, address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(VToken(vTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral)); 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 = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in vToken.liquidateBorrowFresh) * @param vTokenCollateral The address of the collateral vToken * @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens * @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation) */ function liquidateVAICalculateSeizeTokens(address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = 1e18; // Note: this is VAI uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral)); if (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 = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); 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(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the 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); } /** * @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 */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param vToken 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(VToken vToken, 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(vToken)]; 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(vToken) == 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(vToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); 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); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param vToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(VToken vToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(vToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } vToken.isVToken(); // Sanity check to make sure its really a VToken // Note that isVenus is not in active use anymore markets[address(vToken)] = Market({isListed: true, isVenus: false, collateralFactorMantissa: 0}); _addMarketInternal(vToken); emit MarketListed(vToken); return uint(Error.NO_ERROR); } function _addMarketInternal(VToken vToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != vToken, "market already added"); } allMarkets.push(vToken); } /** * @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, newPauseGuardian); return uint(Error.NO_ERROR); } /** * @notice Set the given borrow caps for the given vToken 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 vTokens 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(VToken[] calldata vTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = vTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(vTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(vTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external onlyAdmin { // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Set whole protocol pause/unpause state */ function _setProtocolPaused(bool state) public validPauseState(state) returns(bool) { protocolPaused = state; emit ActionProtocolPaused(state); return state; } /** * @notice Sets a new VAI controller * @dev Admin function to set a new VAI controller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setVAIController(VAIControllerInterface vaiController_) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAICONTROLLER_OWNER_CHECK); } VAIControllerInterface oldRate = vaiController; vaiController = vaiController_; emit NewVAIController(oldRate, vaiController_); } function _setVAIMintRate(uint newVAIMintRate) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAI_MINT_RATE_CHECK); } uint oldVAIMintRate = vaiMintRate; vaiMintRate = newVAIMintRate; emit NewVAIMintRate(oldVAIMintRate, newVAIMintRate); return uint(Error.NO_ERROR); } function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external returns (uint) { // Check caller is admin if (!(msg.sender == admin || msg.sender == treasuryGuardian)) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_TREASURY_OWNER_CHECK); } require(newTreasuryPercent < 1e18, "treasury percent cap overflow"); address oldTreasuryGuardian = treasuryGuardian; address oldTreasuryAddress = treasuryAddress; uint oldTreasuryPercent = treasuryPercent; treasuryGuardian = newTreasuryGuardian; treasuryAddress = newTreasuryAddress; treasuryPercent = newTreasuryPercent; emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian); emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress); emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent); return uint(Error.NO_ERROR); } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can"); require(unitroller._acceptImplementation() == 0, "not 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; } /*** Venus Distribution ***/ function setVenusSpeedInternal(VToken vToken, uint venusSpeed) internal { uint currentVenusSpeed = venusSpeeds[address(vToken)]; if (currentVenusSpeed != 0) { // note that XVS speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()}); updateVenusSupplyIndex(address(vToken)); updateVenusBorrowIndex(address(vToken), borrowIndex); } else if (venusSpeed != 0) { // Add the XVS market Market storage market = markets[address(vToken)]; require(market.isListed == true, "venus market is not listed"); if (venusSupplyState[address(vToken)].index == 0 && venusSupplyState[address(vToken)].block == 0) { venusSupplyState[address(vToken)] = VenusMarketState({ index: venusInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (venusBorrowState[address(vToken)].index == 0 && venusBorrowState[address(vToken)].block == 0) { venusBorrowState[address(vToken)] = VenusMarketState({ index: venusInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentVenusSpeed != venusSpeed) { venusSpeeds[address(vToken)] = venusSpeed; emit VenusSpeedUpdated(vToken, venusSpeed); } } /** * @notice Accrue XVS to the market by updating the supply index * @param vToken The market whose supply index to update */ function updateVenusSupplyIndex(address vToken) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; uint supplySpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = VToken(vToken).totalSupply(); uint venusAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); venusSupplyState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Accrue XVS to the market by updating the borrow index * @param vToken The market whose borrow index to update */ function updateVenusBorrowIndex(address vToken, Exp memory marketBorrowIndex) internal { VenusMarketState storage borrowState = venusBorrowState[vToken]; uint borrowSpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(VToken(vToken).totalBorrows(), marketBorrowIndex); uint venusAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(venusAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); venusBorrowState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Calculate XVS accrued by a supplier and possibly transfer it to them * @param vToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute XVS to */ function distributeSupplierVenus(address vToken, address supplier) internal { if (address(vaiVaultAddress) != address(0)) { releaseToVault(); } VenusMarketState storage supplyState = venusSupplyState[vToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: venusSupplierIndex[vToken][supplier]}); venusSupplierIndex[vToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = venusInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = VToken(vToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(venusAccrued[supplier], supplierDelta); venusAccrued[supplier] = supplierAccrued; emit DistributedSupplierVenus(VToken(vToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate XVS 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 vToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute XVS to */ function distributeBorrowerVenus(address vToken, address borrower, Exp memory marketBorrowIndex) internal { if (address(vaiVaultAddress) != address(0)) { releaseToVault(); } VenusMarketState storage borrowState = venusBorrowState[vToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: venusBorrowerIndex[vToken][borrower]}); venusBorrowerIndex[vToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(VToken(vToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(venusAccrued[borrower], borrowerDelta); venusAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerVenus(VToken(vToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate XVS accrued by a VAI minter and possibly transfer it to them * @dev VAI minters will not begin to accrue until after the first interaction with the protocol. * @param vaiMinter The address of the VAI minter to distribute XVS to */ function distributeVAIMinterVenus(address vaiMinter) public { if (address(vaiVaultAddress) != address(0)) { releaseToVault(); } if (address(vaiController) != address(0)) { uint vaiMinterAccrued; uint vaiMinterDelta; uint vaiMintIndexMantissa; uint err; (err, vaiMinterAccrued, vaiMinterDelta, vaiMintIndexMantissa) = vaiController.calcDistributeVAIMinterVenus(vaiMinter); if (err == uint(Error.NO_ERROR)) { venusAccrued[vaiMinter] = vaiMinterAccrued; emit DistributedVAIMinterVenus(vaiMinter, vaiMinterDelta, vaiMintIndexMantissa); } } } /** * @notice Claim all the xvs accrued by holder in all markets and VAI * @param holder The address to claim XVS for */ function claimVenus(address holder) public { return claimVenus(holder, allMarkets); } /** * @notice Claim all the xvs accrued by holder in the specified markets * @param holder The address to claim XVS for * @param vTokens The list of markets to claim XVS in */ function claimVenus(address holder, VToken[] memory vTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimVenus(holders, vTokens, true, true); } /** * @notice Claim all xvs accrued by the holders * @param holders The addresses to claim XVS for * @param vTokens The list of markets to claim XVS in * @param borrowers Whether or not to claim XVS earned by borrowing * @param suppliers Whether or not to claim XVS earned by supplying */ function claimVenus(address[] memory holders, VToken[] memory vTokens, bool borrowers, bool suppliers) public { uint j; if(address(vaiController) != address(0)) { vaiController.updateVenusVAIMintIndex(); } for (j = 0; j < holders.length; j++) { distributeVAIMinterVenus(holders[j]); venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]); } for (uint i = 0; i < vTokens.length; i++) { VToken vToken = vTokens[i]; require(markets[address(vToken)].isListed, "not listed market"); if (borrowers) { Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()}); updateVenusBorrowIndex(address(vToken), borrowIndex); for (j = 0; j < holders.length; j++) { distributeBorrowerVenus(address(vToken), holders[j], borrowIndex); venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]); } } if (suppliers) { updateVenusSupplyIndex(address(vToken)); for (j = 0; j < holders.length; j++) { distributeSupplierVenus(address(vToken), holders[j]); venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]); } } } } /** * @notice Transfer XVS to the user * @dev Note: If there is not enough XVS, we do not perform the transfer all. * @param user The address of the user to transfer XVS to * @param amount The amount of XVS to (possibly) transfer * @return The amount of XVS which was NOT transferred to the user */ function grantXVSInternal(address user, uint amount) internal returns (uint) { XVS xvs = XVS(getXVSAddress()); uint venusRemaining = xvs.balanceOf(address(this)); if (amount > 0 && amount <= venusRemaining) { xvs.transfer(user, amount); return 0; } return amount; } /*** Venus Distribution Admin ***/ /** * @notice Set the amount of XVS distributed per block to VAI Mint * @param venusVAIRate_ The amount of XVS wei per block to distribute to VAI Mint */ function _setVenusVAIRate(uint venusVAIRate_) public onlyAdmin { uint oldVAIRate = venusVAIRate; venusVAIRate = venusVAIRate_; emit NewVenusVAIRate(oldVAIRate, venusVAIRate_); } /** * @notice Set the amount of XVS distributed per block to VAI Vault * @param venusVAIVaultRate_ The amount of XVS wei per block to distribute to VAI Vault */ function _setVenusVAIVaultRate(uint venusVAIVaultRate_) public onlyAdmin { uint oldVenusVAIVaultRate = venusVAIVaultRate; venusVAIVaultRate = venusVAIVaultRate_; emit NewVenusVAIVaultRate(oldVenusVAIVaultRate, venusVAIVaultRate_); } /** * @notice Set the VAI Vault infos * @param vault_ The address of the VAI Vault * @param releaseStartBlock_ The start block of release to VAI Vault * @param minReleaseAmount_ The minimum release amount to VAI Vault */ function _setVAIVaultInfo(address vault_, uint256 releaseStartBlock_, uint256 minReleaseAmount_) public onlyAdmin { vaiVaultAddress = vault_; releaseStartBlock = releaseStartBlock_; minReleaseAmount = minReleaseAmount_; emit NewVAIVaultInfo(vault_, releaseStartBlock_, minReleaseAmount_); } /** * @notice Set XVS speed for a single market * @param vToken The market whose XVS speed to update * @param venusSpeed New XVS speed for market */ function _setVenusSpeed(VToken vToken, uint venusSpeed) public { require(adminOrInitializing(), "only admin can set venus speed"); setVenusSpeedInternal(vToken, venusSpeed); } /** * @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 (VToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the XVS token * @return The address of XVS */ function getXVSAddress() public view returns (address) { return 0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63; } /*** VAI functions ***/ /** * @notice Set the minted VAI amount of the `owner` * @param owner The address of the account to set * @param amount The amount of VAI to set to the account * @return The number of minted VAI by `owner` */ function setMintedVAIOf(address owner, uint amount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintVAIGuardianPaused && !repayVAIGuardianPaused, "VAI is paused"); // Check caller is vaiController if (msg.sender != address(vaiController)) { return fail(Error.REJECTION, FailureInfo.SET_MINTED_VAI_REJECTION); } mintedVAIs[owner] = amount; return uint(Error.NO_ERROR); } /** * @notice Transfer XVS to VAI Vault */ function releaseToVault() public { if(releaseStartBlock == 0 || getBlockNumber() < releaseStartBlock) { return; } XVS xvs = XVS(getXVSAddress()); uint256 xvsBalance = xvs.balanceOf(address(this)); if(xvsBalance == 0) { return; } uint256 actualAmount; uint256 deltaBlocks = sub_(getBlockNumber(), releaseStartBlock); // releaseAmount = venusVAIVaultRate * deltaBlocks uint256 _releaseAmount = mul_(venusVAIVaultRate, deltaBlocks); if (_releaseAmount < minReleaseAmount) { return; } if (xvsBalance >= _releaseAmount) { actualAmount = _releaseAmount; } else { actualAmount = xvsBalance; } releaseStartBlock = getBlockNumber(); xvs.transfer(vaiVaultAddress, actualAmount); emit DistributedVAIVaultVenus(actualAmount); IVAIVault(vaiVaultAddress).updatePendingRewards(); } }
Set the given borrow caps for the given vToken markets. Borrowing that brings total borrows to or above borrow cap will revert. Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. vTokens The addresses of the markets (tokens) to change the borrow caps for newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing./
function _setMarketBorrowCaps(VToken[] calldata vTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = vTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(vTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(vTokens[i], newBorrowCaps[i]); } }
1,063,706
pragma solidity 0.4.25; import "./SafeMath.sol"; import "./Roles.sol"; /** * @title TRC20 interface */ interface TRC20Interface { function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title Standard TRC20 token * @dev Implementation of the basic standard token. */ contract TRC20 is TRC20Interface { using SafeMath for uint256; uint256 public totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; function() public payable { revert(); } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public view returns (uint256) { return balances[tokenOwner]; } /** * @dev Function to check the amount of tokens that an tokenOwner allowed to a * spender. * @param tokenOwner 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 tokenOwner, address spender) public view returns (uint256) { return allowed[tokenOwner][spender]; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param tokens The amount to be transferred. */ function transfer(address to, uint256 tokens) public returns (bool) { require(to != address(0)); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); 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: * @param spender The address which will spend the funds. * @param tokens The amount of tokens to be spent. */ function approve(address spender, uint256 tokens) public returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /** * @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 tokens uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 tokens) public returns (bool) { require(to != address(0)); require(tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } }
TRC20 interface/
interface TRC20Interface { function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); }
12,758,007
pragma solidity 0.4.24; import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title One-time schedulable contract * @author Jakub Stefanski (https://github.com/jstefanski) */ contract Schedulable is Ownable { /** * @dev First block when contract is active (inclusive). Zero if not scheduled. */ uint256 public startBlock; /** * @dev Last block when contract is active (inclusive). Zero if not scheduled. */ uint256 public endBlock; /** * @dev Contract scheduled within given blocks * @param startBlock uint256 The first block when contract is active (inclusive) * @param endBlock uint256 The last block when contract is active (inclusive) */ event Scheduled(uint256 startBlock, uint256 endBlock); modifier onlyNotZero(uint256 value) { require(value != 0); _; } modifier onlyScheduled() { require(isScheduled()); _; } modifier onlyNotScheduled() { require(!isScheduled()); _; } modifier onlyActive() { require(isActive()); _; } modifier onlyNotActive() { require(!isActive()); _; } /** * @dev Schedule contract activation for given block range * @param _startBlock uint256 The first block when contract is active (inclusive) * @param _endBlock uint256 The last block when contract is active (inclusive) */ function schedule(uint256 _startBlock, uint256 _endBlock) public onlyOwner onlyNotScheduled onlyNotZero(_startBlock) onlyNotZero(_endBlock) { require(_startBlock < _endBlock); startBlock = _startBlock; endBlock = _endBlock; emit Scheduled(_startBlock, _endBlock); } /** * @dev Check whether activation is scheduled */ function isScheduled() public view returns (bool) { return startBlock > 0 && endBlock > 0; } /** * @dev Check whether contract is currently active */ function isActive() public view returns (bool) { return block.number >= startBlock && block.number <= endBlock; } }
Schedule contract activation for given block range _startBlock uint256 The first block when contract is active (inclusive) _endBlock uint256 The last block when contract is active (inclusive)/
function schedule(uint256 _startBlock, uint256 _endBlock) public onlyOwner onlyNotScheduled onlyNotZero(_startBlock) onlyNotZero(_endBlock) { require(_startBlock < _endBlock); startBlock = _startBlock; endBlock = _endBlock; emit Scheduled(_startBlock, _endBlock); }
12,856,306
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ 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 pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <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; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract 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 virtual 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 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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <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; // solhint-disable-next-line no-inline-assembly 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"); // 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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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 // 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 pragma solidity >=0.6.0 <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; // 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]; } // 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)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <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 { // 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 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) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @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) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @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) { 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(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)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.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--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.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 ^ 0xe985e9c5 ^ 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 virtual 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 virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _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)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, 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 virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual 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 virtual 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 = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.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 = ERC721.ownerOf(tokenId); // internal owner _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(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner 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); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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/Ownable.sol pragma solidity >=0.6.0 <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 () internal { 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; } } /* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______ | || || | | || | | || | | || | | _ || || | | _ || | | | | || | | ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___| | | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___ | || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___| | |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___ |_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______| */ pragma solidity ^0.7.0; contract GeniculateBlue is ERC721, Ownable { constructor() ERC721("Geniculate Blue", "LGN") {} using SafeMath for uint256; uint256 public constant nftPrice = 550000000000000000; uint public constant MAX_PURCHASE = 11; uint256 public constant MAX_MAIN = 475; bool public saleIsActive = false; uint public teamReserve = 15; function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function reserve(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More."); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } teamReserve = teamReserve.sub(_reserveAmount); } function mint(uint _numberOfTokens) public payable { require(saleIsActive, "Not Active."); require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit."); require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted."); require(msg.value >= nftPrice, "More Ethereum."); for(uint i = 0; i < _numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_MAIN) { _safeMint(msg.sender, mintIndex); } } } string public mintedCode; bool public isReconstructed = false; mapping (uint256 => string) public geniculateSeeds; mapping (uint256 => bool) public seedSet; mapping (uint => string) public mintedColors; event SeedWritten (uint256 indexed nameIndex, string newName); function setSeed(uint256 _tokenId, string calldata currName) public { address owner = ownerOf(_tokenId); require(msg.sender == owner, "Incorrect."); require(seedSet[_tokenId] == false, "Name given."); seedSet[_tokenId] = true; geniculateSeeds[_tokenId] = currName; emit SeedWritten(_tokenId, currName); } function viewSeed(uint _tokenId) public view returns(string memory){ return geniculateSeeds[_tokenId]; } function setCode(string calldata currName) public onlyOwner { mintedCode = currName; } function viewCode() public view returns(string memory) { return mintedCode; } function setColors(uint palette, string calldata palette_param) public onlyOwner { mintedColors[palette] = palette_param; } function viewColors(uint palette) public view returns(string memory) { return mintedColors[palette]; } }
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)))); }
2,048,129
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./interfaces/ITimeBasedSwitch.sol"; import "./interfaces/KeeperCompatibleInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; contract TimeBasedSwitch is ITimeBasedSwitch, Ownable, ReentrancyGuard, IERC721Receiver, KeeperCompatibleInterface { using SafeMath for uint256; using SafeERC20 for IERC20; /* Structs */ struct NFT { uint id; // Id of the specific collectible address tokenAddress; // Collectible's contract address address benefitor; // Wallet to get specific collectible after execution of the switch } struct Switch { uint amount; // amount locked (in eth) uint unlockTimestamp; // minimum block to unlock eth bytes32 switchName; // name of the switch address executor; // account allowed to try execute a switch address payable benefitor; // account for eth to be transfered to bool isValid; // check validity of existing switch if exists address[] tokensLocked; // addresses of all erc20 tokens locked in a switch, keys of the tokens mapping mapping(address => uint) tokens; // erc20 token address => amount locked NFT[] collectiblesLocked; // list of addresses of all erc721 tokens locked in switch } /* Storage */ address internal keeperRegistry; address[] internal scheduledSwitches; mapping(address => Switch) internal users; //store switch per user account /* Modifiers */ /** * @notice Checks that the the account passed is a valid switch * @dev To be used in any situation where the function performs a check of existing/valid switches * @param account The account to check the validity of */ modifier onlyValid(address account) { require(users[account].isValid && users[account].amount > 0, "Not a valid account query"); _; } /** * @notice Checks that the the function is being called only by the involved parties * @dev To be used in any situation where the function performs a privledged action to the switch * @param account The account to check the owner of */ modifier onlyAllowed(address account) { require(users[account].benefitor == msg.sender || users[account].executor == msg.sender || account == msg.sender, "You do not have rights to check on this switch!"); _; } /** * @notice Checks that the the function is being called only by the executor of the switch * @dev To be used in any situation where the function performs a privledged action to the switch * @param account The account to check the owner of */ modifier onlyExecutorsOrOwner(address account) { require(users[account].executor == msg.sender || (users[msg.sender].isValid && msg.sender == account), "You do not have rights to execute this switch!"); _; } /** * @notice Checks that a specified amount matches the msg.value sent * @dev To be used in any situation where we check that user is sending exact amount specified * @param amount The amount to be checked */ modifier checkAmount(uint amount) { require(msg.value == amount, "Must send exact amount"); _; } /** * @notice Checks that a specified time parameter is set to minimum 1 day * @dev To be used in any situation where we check that user is setting unlock time minimum 1 day a head * @param time The time to be checked */ modifier checkTime(uint time) { require(time >= block.timestamp + 86400, "One day is minimum time for switch"); //86400 seconds = 1 day _; } /** * @notice Checks that a switch doesnt exist or isnt valid * @dev To be used in any situation where we want to make sure that a switch is not set for this account or is invalidated like when creating new switch */ modifier doesntExist() { require(!users[msg.sender].isValid && users[msg.sender].amount == 0, "Switch for this account already exist"); _; } /* Functions */ /// @notice Constructor function which establishes two payout addresses for fees and fee amount constructor(address _keeperRegistry) public { keeperRegistry = _keeperRegistry; } /// @notice The fallback function for the contract /// @dev Will simply accept any unexpected eth, but no data receive() payable external { emit EtherReceived(msg.sender, msg.value); } /// @inheritdoc ITimeBasedSwitch function createSwitch(bytes32 _switchName, uint _time, uint _amount, address _executor, address payable _benefitor) public payable override doesntExist checkAmount(_amount) checkTime(_time) { require(msg.sender != _benefitor,'creator can not be one of the benefitors'); users[msg.sender].switchName = _switchName; users[msg.sender].unlockTimestamp = _time; users[msg.sender].executor = _executor; users[msg.sender].benefitor = _benefitor; users[msg.sender].amount = _amount; users[msg.sender].isValid = true; if (_executor == keeperRegistry) { scheduledSwitches.push(msg.sender); } emit SwitchCreated( _switchName, users[msg.sender].unlockTimestamp, _executor, _benefitor, _amount ); } /// @inheritdoc ITimeBasedSwitch function lockToken(address _tokenAddress, uint256 _amount) public override onlyValid(msg.sender) { require(_tokenAddress != address(0), "lockToken: Invalid token address"); require(_amount > 0, "lockToken: Amount must be greater than 0"); uint256 tokenAmount = users[msg.sender].tokens[_tokenAddress]; IERC20(_tokenAddress).safeTransferFrom(msg.sender, address(this), _amount); if(tokenAmount == 0) { users[msg.sender].tokensLocked.push(_tokenAddress); } users[msg.sender].tokens[_tokenAddress] = tokenAmount.add(_amount); emit TokenLocked(msg.sender, _tokenAddress, _amount); } /// @inheritdoc ITimeBasedSwitch function lockCollectible(address _tokenAddress, uint256 _tokenId) public override onlyValid(msg.sender) { require(_tokenAddress != address(0), "lockCollectible: Invalid token address"); ERC721(_tokenAddress).safeTransferFrom(msg.sender, address(this), _tokenId); emit CollectibleLocked(msg.sender, _tokenAddress, _tokenId, users[msg.sender].benefitor); } /// @inheritdoc IERC721Receiver /// @notice the ERC721 contract address is always the message sender. function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns(bytes4) { users[from].collectiblesLocked.push(NFT(tokenId, msg.sender, users[from].benefitor)); return 0x150b7a02; } /// @inheritdoc ITimeBasedSwitch function terminateSwitchEarly() public payable override onlyValid(msg.sender) nonReentrant { uint remains = users[msg.sender].amount; users[msg.sender].amount = 0; users[msg.sender].isValid = false; (bool success, ) = msg.sender.call{value: remains}(""); require(success, 'transfer failed'); for(uint i = 0; i < users[msg.sender].tokensLocked.length; i++) { address tokenToWithdraw = users[msg.sender].tokensLocked[i]; withdrawToken(tokenToWithdraw, users[msg.sender].tokens[tokenToWithdraw], msg.sender); } uint collectiblesLength = users[msg.sender].collectiblesLocked.length; for(uint i = 0; i < collectiblesLength; i++) { NFT storage currentCollectible = users[msg.sender].collectiblesLocked[i]; withdrawCollectible(currentCollectible.tokenAddress, currentCollectible.id, msg.sender); } if (users[msg.sender].executor == keeperRegistry) { deleteScheduledSwitch(msg.sender); } delete users[msg.sender]; emit SwitchTerminated(msg.sender); } /// @inheritdoc ITimeBasedSwitch function tryExecuteSwitch(address account) public payable override onlyValid(account) onlyExecutorsOrOwner(account) nonReentrant { require(block.timestamp >= users[account].unlockTimestamp,'this switch has not expired yet'); uint amount = users[account].amount; users[account].amount = 0; users[account].isValid = false; (bool success, ) = users[account].benefitor.call{value: amount}(""); require(success, 'transfer failed'); for(uint i = 0; i < users[account].tokensLocked.length; i++) { address tokenToWithdraw = users[account].tokensLocked[i]; withdrawToken(tokenToWithdraw, users[account].tokens[tokenToWithdraw], users[account].benefitor); } uint collectiblesLength = users[account].collectiblesLocked.length; for(uint i = 0; i < collectiblesLength; i++) { NFT storage currentCollectible = users[account].collectiblesLocked[i]; withdrawCollectible(currentCollectible.tokenAddress, currentCollectible.id, currentCollectible.benefitor); } emit SwitchTriggered(account); delete users[account]; emit SwitchTerminated(account); } /// @inheritdoc ITimeBasedSwitch function updateSwitchAmount() public payable override onlyValid(msg.sender) { require(msg.value > 0 , 'must send some amount'); users[msg.sender].amount = users[msg.sender].amount.add(msg.value); emit AmountUpdated(msg.value); } /// @inheritdoc ITimeBasedSwitch function updateSwitchUnlockTime(uint _unlockTimestamp) public payable override onlyValid(msg.sender) checkTime(_unlockTimestamp) { users[msg.sender].unlockTimestamp = _unlockTimestamp; emit UnlockTimeUpdated(_unlockTimestamp); } /// @inheritdoc ITimeBasedSwitch function updateSwitchExecutor(address _executor) public payable override onlyValid(msg.sender) { if (_executor == keeperRegistry) { scheduledSwitches.push(msg.sender); } if (users[msg.sender].executor == keeperRegistry && _executor != keeperRegistry) { deleteScheduledSwitch(msg.sender); } users[msg.sender].executor = _executor; emit ExecutorUpdated(_executor); } /// @inheritdoc ITimeBasedSwitch function updateSwitchBenefitor(address payable _benefitor) public payable override onlyValid(msg.sender) { users[msg.sender].benefitor = _benefitor; emit BenefitorUpdated(_benefitor); } /// @inheritdoc ITimeBasedSwitch function getSwitchInfo(address _switchOwner) public view override onlyValid(_switchOwner) onlyAllowed(_switchOwner) returns (bytes32, uint, uint, address, address, bool) { return ( users[_switchOwner].switchName, users[_switchOwner].amount, users[_switchOwner].unlockTimestamp, users[_switchOwner].executor, users[_switchOwner].benefitor, users[_switchOwner].isValid ); } /// @inheritdoc KeeperCompatibleInterface function checkUpkeep(bytes calldata checkData) public view override returns(bool upkeepNeeded, bytes memory performData) { uint i = 0; uint length = scheduledSwitches.length; bool isExpired = false; address currentSwitch = address(0); while(i < length && !isExpired) { currentSwitch = scheduledSwitches[i]; isExpired = block.timestamp >= users[currentSwitch].unlockTimestamp; i++; } upkeepNeeded = isExpired; performData = abi.encodePacked(currentSwitch); } /// @inheritdoc KeeperCompatibleInterface function performUpkeep(bytes calldata performData) public override { require(msg.sender == keeperRegistry); address account = bytesToAddress(performData); deleteScheduledSwitch(account); tryExecuteSwitch(account); } /** * @notice Updates Keeper Registry Contract Address * @notice Only Administrator can call * * @param _keeperRegistry - new Keeper Registry Contract Address * * No return, reverts on error */ function setKeeperRegistry(address _keeperRegistry) public onlyOwner { keeperRegistry = _keeperRegistry; emit KeeperRegistryUpdated(_keeperRegistry); } /** * @notice Function to withdraw amount of given ERC20 token * * @param _tokenAddress - address of ERC20 token * @param _amount - amount to withdraw * @param _receiver - address of wallet to receive tokens * * No return, reverts on error */ function withdrawToken(address _tokenAddress, uint256 _amount, address _receiver) private { require(_tokenAddress != address(0), "withdrawToken: Invalid token address"); require(_amount > 0, "withdrawToken: Amount must be greater than 0"); require(_receiver != address(0), "withdrawToken: Invalid receiver address"); users[msg.sender].tokens[_tokenAddress] = users[msg.sender].tokens[_tokenAddress].sub(_amount); IERC20(_tokenAddress).safeTransfer(_receiver, _amount); } /** * @notice Function to withdraw ERC721 collectible * * @param _tokenAddress - address of ERC721 token * @param _tokenId - id of colletible * @param _receiver - address of wallet to receive collectible * * No return, reverts on error */ function withdrawCollectible(address _tokenAddress, uint256 _tokenId, address _receiver) private { require(_tokenAddress != address(0), "withdrawCollectible: Invalid token address"); require(_receiver != address(0), "withdrawCollectible: Invalid receiver address"); ERC721(_tokenAddress).safeTransferFrom(address(this), _receiver, _tokenId); } /** * @notice Function to delete address from Bot Scheduled Switches array * * @param user - address of switch to delete * * No return, reverts on error */ function deleteScheduledSwitch(address user) private { uint length = scheduledSwitches.length; for (uint i = 0; i < length; i++) { if (scheduledSwitches[i] == user) { scheduledSwitches[i] = scheduledSwitches[length - 1]; scheduledSwitches.pop(); return; } } } /** * @notice Function to convert Ethereum address from bytes format to address format * * @param inputBytes - bytes to convert * * @param outputAddress - converted address */ function bytesToAddress(bytes memory inputBytes) private pure returns(address outputAddress) { uint256 bytesLength = inputBytes.length; assembly { outputAddress := mload(add(inputBytes, bytesLength)) } } }
Function to withdraw amount of given ERC20 token _tokenAddress - address of ERC20 token _amount - amount to withdraw _receiver - address of wallet to receive tokens No return, reverts on error/
function withdrawToken(address _tokenAddress, uint256 _amount, address _receiver) private { require(_tokenAddress != address(0), "withdrawToken: Invalid token address"); require(_amount > 0, "withdrawToken: Amount must be greater than 0"); require(_receiver != address(0), "withdrawToken: Invalid receiver address"); users[msg.sender].tokens[_tokenAddress] = users[msg.sender].tokens[_tokenAddress].sub(_amount); IERC20(_tokenAddress).safeTransfer(_receiver, _amount); }
937,245
./full_match/43114/0xa14f8c2fD5A335aCb230834D6A57750046a5c4Df/sources/contracts/ERC721Art.sol
only ownerTokenCount
function airdrop(address[] memory _to) public onlyOwner { uint arrayLength = _to.length; require((airdropCount + arrayLength) < airdropMax, "Cannot exceed Airdrop Cap"); for (uint i=0; i<arrayLength; i++) { _privateMint(_to[i], 1); airdropCount++; } }
4,540,000
// SPDX-License-Identifier: MIT // 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); function decimals() external view returns (uint8); /** * @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/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); /** * Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * Returns the address of the current owner. */ function governance() public view returns (address) { return _owner; } /** * Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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 () internal { _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; } } // File: contracts/ReethMonetaryPolicyV2.sol pragma solidity =0.6.6; // This monetary policy controls the rebase mechanism in the reeth token // Rebase can only be called once a day by a non-contract // To incentivize rebase, the policy will mint reeth to the delegatecaller equal to up to the fast gas price (determined by Chainlink) // There is an absolute max price however interface PriceOracle { function getLatestREETHPrice() external view returns (uint256); function updateREETHPrice() external; // Update price oracle upon every token transfer function mainLiquidity() external view returns (address); // Returns address of REETH/ETH LP pair } interface AggregatorV3Interface { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } interface UniswapLikeLPToken { function sync() external; // Call sync right after rebase call } interface ReethToken { function mint(address, uint256) external returns (bool); function isRebaseable() external view returns (bool); function reethScalingFactor() external view returns (uint256); function maxScalingFactor() external view returns (uint256); function rebase(uint256 _price, uint256 _indexDelta, bool _positive) external returns (uint256); // Epoch is stored in the token } contract ReethMonetaryPolicyV2 is Ownable, ReentrancyGuard { // Adopted from YamRebaserV2 using SafeMath for uint256; /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; /// @notice Reeth token address address public reethAddress; // price oracle address address public reethPriceOracle; /// @notice list of uniswap like pairs to sync address[] public uniSyncPairs; // Used for division scaling math uint256 constant BASE = 1e18; address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle // Gas price maximum uint256 public maxGasPrice = 200000000000; // 200 Gwei uint256 public callerBonus = 5000; // Rebase caller gets a initial bonus of 5% event RebaseMint(uint256 _gasCost, uint256 _reethMinted, address _receiver); constructor( address _reethAddress, address _priceOracle ) public { reethAddress = _reethAddress; reethPriceOracle = _priceOracle; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 12 hours; // 12:00 UTC rebase // 1 REETH = 1 ETH targetRate = BASE; // once daily rebase, with targeting reaching peg in 10 days rebaseLag = 10; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 1 hours; } // This is an optional function that is ran anytime a reeth transfer is made function reethTransferActions() external { require(_msgSender() == reethAddress, "Not sent from REETH token"); // We are running the price oracle update if(reethPriceOracle != address(0)){ PriceOracle oracle = PriceOracle(reethPriceOracle); oracle.updateREETHPrice(); // Update the price of reeth } } // Rebase function /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ // Users can give their gas spent to another user if they choose to (in case of bot calls) function rebase(address _delegateCaller) public { // Users will be recognized for 1.5x the eth they spend when using this oracle uint256 gasUsed = gasleft(); // Start calculate gas spent // EOA only or gov require(_msgSender() == tx.origin || _msgSender() == governance(), "Contract call not allowed unless governance"); // ensure rebasing at correct time require(inRebaseWindow() == true, "Not in rebase window"); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "Call already executed for this epoch"); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); PriceOracle oracle = PriceOracle(reethPriceOracle); oracle.updateREETHPrice(); // Update the price of reeth uint256 exchangeRate = oracle.getLatestREETHPrice(); require(exchangeRate > 0, "Bad oracle price"); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); ReethToken reeth = ReethToken(reethAddress); if (positive) { require(reeth.reethScalingFactor().mul(BASE.add(indexDelta)).div(BASE) < reeth.maxScalingFactor(), "new scaling factor will be too big"); } // rebase the token reeth.rebase(exchangeRate, indexDelta, positive); // sync the pools { // first sync the main pool address mainLP = oracle.mainLiquidity(); UniswapLikeLPToken lp = UniswapLikeLPToken(mainLP); lp.sync(); // Sync this pool post rebase // And any additional pairs to sync for(uint256 i = 0; i < uniSyncPairs.length; i++){ lp = UniswapLikeLPToken(uniSyncPairs[i]); lp.sync(); } } // Determine what gas price to use when minting reeth // We do this instead of updating the spent ETH oracle to incentivize calling rebase uint256 gasPrice = tx.gasprice; { uint256 fastPrice = getFastGasPrice(); if(gasPrice > fastPrice){ gasPrice = fastPrice; } if(gasPrice > maxGasPrice){ gasPrice = maxGasPrice; } } if(_delegateCaller == address(0)){ _delegateCaller = _msgSender(); } gasUsed = gasUsed.sub(gasleft()).mul(gasPrice).mul(100000 + callerBonus).div(100000); // The amount of ETH reimbursed for this transaction with bonus // Convert ETH units to REETH units and mint to delegated caller uint256 reethReturn = gasUsed.mul(10**uint256(IERC20(reethAddress).decimals())).div(1e18); reethReturn = reethReturn.mul(1e18).div(exchangeRate); if(reethReturn > 0){ reeth.mint(_delegateCaller, reethReturn); emit RebaseMint(gasUsed, reethReturn, _delegateCaller); } } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // First check if reeth token is active for rebasing if(ReethToken(reethAddress).isRebaseable() == false){return false;} return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(BASE).div(targetRate), true); } else { return (targetRate.sub(rate).mul(BASE).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } function getFastGasPrice() public view returns (uint256) { AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS); ( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer return uint256(intGasPrice); } // Governance only functions // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; uint256[3] private _timelock_data; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met"); _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Add to the synced pairs // -------------------- function startAddSyncPair(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishAddSyncPair() external onlyGovernance timelockConditionsMet(2) { uniSyncPairs.push(_timelock_address); } // -------------------- // Remove from synced pairs // -------------------- function startRemoveSyncPair(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 3; _timelock_address = _address; } function finishRemoveSyncPair() external onlyGovernance timelockConditionsMet(3) { uint256 length = uniSyncPairs.length; for(uint256 i = 0; i < length; i++){ if(uniSyncPairs[i] == _timelock_address){ for(uint256 i2 = i; i2 < length-1; i2++){ uniSyncPairs[i2] =uniSyncPairs[i2 + 1]; // Shift the data down one } uniSyncPairs.pop(); //Remove last element break; } } } // -------------------- // Change the deviation threshold // -------------------- function startChangeDeviationThreshold(uint256 _threshold) external onlyGovernance { require(_threshold > 0); _timelockStart = now; _timelockType = 4; _timelock_data[0] = _threshold; } function finishChangeDeviationThreshold() external onlyGovernance timelockConditionsMet(4) { deviationThreshold = _timelock_data[0]; } // -------------------- // Change the rebase lag // -------------------- function startChangeRebaseLag(uint256 _lag) external onlyGovernance { require(_lag > 1); _timelockStart = now; _timelockType = 5; _timelock_data[0] = _lag; } function finishChangeRebaseLag() external onlyGovernance timelockConditionsMet(5) { rebaseLag = _timelock_data[0]; } // -------------------- // Change the target rate // -------------------- function startChangeTargetRate(uint256 _rate) external onlyGovernance { require(_rate > 0); _timelockStart = now; _timelockType = 6; _timelock_data[0] = _rate; } function finishChangeTargetRate() external onlyGovernance timelockConditionsMet(6) { targetRate = _timelock_data[0]; } // -------------------- // Change the rebase times // -------------------- function startChangeRebaseTimes(uint256 _UTCOffset, uint256 _windowLength, uint256 _frequency) external onlyGovernance { require(_frequency > 0); require(_UTCOffset < _frequency); require(_UTCOffset + _windowLength < _frequency); _timelockStart = now; _timelockType = 7; _timelock_data[0] = _UTCOffset; _timelock_data[1] = _windowLength; _timelock_data[2] = _frequency; } function finishChangeRebaseTimes() external onlyGovernance timelockConditionsMet(7) { rebaseWindowOffsetSec = _timelock_data[0]; rebaseWindowLengthSec = _timelock_data[1]; minRebaseTimeIntervalSec = _timelock_data[2]; } // -------------------- // Change the max gas allowed // -------------------- function startChangeMaxGasPrice(uint256 _gas) external onlyGovernance { _timelockStart = now; _timelockType = 8; _timelock_data[0] = _gas; } function finishChangeMaxGasPrice() external onlyGovernance timelockConditionsMet(8) { maxGasPrice = _timelock_data[0]; } // -------------------- // Change the caller bonus // -------------------- function startChangeCallerBonus(uint256 _bonus) external onlyGovernance { require(_bonus < 100000, "Bonus is too high"); _timelockStart = now; _timelockType = 9; _timelock_data[0] = _bonus; } function finishChangeCallerBonus() external onlyGovernance timelockConditionsMet(9) { callerBonus = _timelock_data[0]; } // -------------------- }
return If the latest block timestamp is within the rebase time window it, returns true. Otherwise, returns false./ First check if reeth token is active for rebasing
function inRebaseWindow() public view returns (bool) { return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))); }
13,387,919
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./interface/ISqwidMarketplace.sol"; contract SqwidGovernance { struct Transaction { address to; uint256 value; bytes data; bool executed; uint256 numConfirmations; } struct OwnersChange { address ownerChanged; bool addToList; uint256 numConfirmations; } struct MinConfirmationsChange { uint256 newValue; uint256 numConfirmations; } address[] private owners; uint256 public minConfirmationsRequired; mapping(address => uint256) public addressBalance; mapping(address => bool) public isOwner; Transaction[] public transactions; // mapping from tx index => owner => bool mapping(uint256 => mapping(address => bool)) public txApproved; OwnersChange[] public ownersChanges; // mapping from owner change index => owner => bool mapping(uint256 => mapping(address => bool)) public ownersChangeApproved; MinConfirmationsChange[] public minConfirmationsChanges; // mapping from min confirmation change index => owner => bool mapping(uint256 => mapping(address => bool)) public minConfirmationsChangeApproved; event ProposeTransaction( address owner, uint256 indexed txIndex, address ownerChanged, uint256 value, bytes data ); event ExecuteTransaction(address owner, uint256 indexed txIndex); event ProposeOwnersChange( address owner, uint256 indexed ownersChangeIndex, address ownerChanged, bool addToList ); event ExecuteOwnersChange(address owner, uint256 indexed ownersChangeIndex); event ProposeMinConfirmationsChange( address owner, uint256 indexed minConfirmationsChangeIndex, uint256 newValue ); event ExecuteMinConfirmationsChange(address owner, uint256 indexed minConfirmationsChangeIndex); modifier onlyOwner() { require(isOwner[msg.sender], "Governance: Caller is not owner"); _; } modifier txExists(uint256 _txIndex) { require(_txIndex < transactions.length, "Governance: Tx does not exist"); _; } modifier txNotExecuted(uint256 _txIndex) { require(!transactions[_txIndex].executed, "Governance: Tx already executed"); _; } modifier ownersChangeExists(uint256 _ownersChangeIndex) { require( _ownersChangeIndex < ownersChanges.length, "Governance: Owners change does not exist" ); _; } modifier minConfirmationsChangeExists(uint256 _minConfirmationsChangeIndex) { require( _minConfirmationsChangeIndex < minConfirmationsChanges.length, "Governance: Min confirmations change does not exist" ); _; } constructor(address[] memory _owners, uint256 _minConfirmationsRequired) { require(_owners.length > 0, "Governance: Owners required"); require( _minConfirmationsRequired > 0 && _minConfirmationsRequired <= _owners.length, "Governance: Invalid minimum confirmations" ); for (uint256 i; i < _owners.length; i++) { address owner = _owners[i]; require(owner != address(0), "Governance: Invalid owner"); require(!isOwner[owner], "Governance: Owner not unique"); isOwner[owner] = true; owners.push(owner); } minConfirmationsRequired = _minConfirmationsRequired; } receive() external payable {} ///////////////////////////// TX WITHOUT APPROVAL ///////////////////////////////////// ///////////////////// Any of the owners can execute them ////////////////////////////// /** * Withdraws available balance from marketplace contract. */ function transferFromMarketplace(ISqwidMarketplace _marketplace) external onlyOwner { _marketplace.withdraw(); } /** * Returns available balance to be shared among all the owners. */ function getAvailableBalance() public view returns (uint256) { uint256 availableBalance = address(this).balance; for (uint256 i; i < owners.length; i++) { availableBalance -= addressBalance[owners[i]]; } return availableBalance; } /** * Shares available balance (if any) among all the owners and increments their balances. * Withdraws balance of the caller. */ function withdraw() external onlyOwner { uint256 availableBalance = getAvailableBalance(); if (availableBalance >= owners.length) { uint256 share = availableBalance / owners.length; for (uint256 i; i < owners.length; i++) { addressBalance[owners[i]] += share; } } uint256 amount = addressBalance[msg.sender]; require(amount > 0, "Governance: No Reef to be claimed"); addressBalance[msg.sender] = 0; (bool success, ) = msg.sender.call{ value: amount }(""); require(success, "Governance: Error sending REEF"); } /** * Returns array of owners. */ function getOwners() external view returns (address[] memory) { return owners; } /** * Returns total number of transaction proposals. */ function transactionsCount() external view returns (uint256) { return transactions.length; } /** * Returns total number of owners change proposals. */ function ownersChangesCount() external view returns (uint256) { return ownersChanges.length; } /** * Returns total number of minimum confirmations change proposals. */ function minConfirmationsChangesCount() external view returns (uint256) { return minConfirmationsChanges.length; } //////////////////////// EXTERNAL TX WITH APPROVAL //////////////////////////////////// ///////////// Requires a minimum of confirmations to be executed ////////////////////// /** * Creates a proposal for an external transaction. * `_to`: address to be called * `_value`: value of Reef to be sent * `_data`: data to be sent */ function proposeTransaction( address _to, uint256 _value, bytes memory _data ) external onlyOwner { uint256 txIndex = transactions.length; transactions.push( Transaction({ to: _to, value: _value, data: _data, executed: false, numConfirmations: 0 }) ); approveTransaction(txIndex); emit ProposeTransaction(msg.sender, txIndex, _to, _value, _data); } /** * Approves a transaction. */ function approveTransaction(uint256 _txIndex) public onlyOwner txExists(_txIndex) txNotExecuted(_txIndex) { require(!txApproved[_txIndex][msg.sender], "Governance: Tx already approved"); Transaction storage transaction = transactions[_txIndex]; transaction.numConfirmations++; txApproved[_txIndex][msg.sender] = true; } /** * Executes a transaction. * It should have the minimum number of confirmations required in order to be executed. */ function executeTransaction(uint256 _txIndex) public onlyOwner txExists(_txIndex) txNotExecuted(_txIndex) { Transaction storage transaction = transactions[_txIndex]; require( transaction.numConfirmations >= minConfirmationsRequired, "Governance: Tx not approved" ); transaction.executed = true; (bool success, ) = transaction.to.call{ value: transaction.value }(transaction.data); require(success, "Governance: tx failed"); emit ExecuteTransaction(msg.sender, _txIndex); } //////////////////////// INTERNAL TX WITH APPROVAL //////////////////////////////////// ///////////// Requires a minimum of confirmations to be executed ////////////////////// /** * Creates a proposal for a change in the list of owners. * `_ownerChanged`: address of the owner to be changed * `_addToList`: true --> add new owner / false --> remove existing owner */ function proposeOwnersChange(address _ownerChanged, bool _addToList) external onlyOwner { uint256 ownersChangeIndex = ownersChanges.length; ownersChanges.push( OwnersChange({ ownerChanged: _ownerChanged, addToList: _addToList, numConfirmations: 0 }) ); approveOwnersChange(ownersChangeIndex); emit ProposeOwnersChange(msg.sender, ownersChangeIndex, _ownerChanged, _addToList); } /** * Approves a change in the owners list. */ function approveOwnersChange(uint256 _ownersChangeIndex) public onlyOwner ownersChangeExists(_ownersChangeIndex) { require( !ownersChangeApproved[_ownersChangeIndex][msg.sender], "Governance: Owners change already approved" ); OwnersChange storage ownersChange = ownersChanges[_ownersChangeIndex]; ownersChange.numConfirmations++; ownersChangeApproved[_ownersChangeIndex][msg.sender] = true; } /** * Executes a change in the owners list. * It should have the minimum number of confirmations required in order to do the change. */ function executeOwnersChange(uint256 _ownersChangeIndex) public onlyOwner ownersChangeExists(_ownersChangeIndex) { OwnersChange storage ownersChange = ownersChanges[_ownersChangeIndex]; require( ownersChange.numConfirmations >= minConfirmationsRequired, "Governance: Owners change not approved" ); if (ownersChange.addToList) { require(!isOwner[ownersChange.ownerChanged], "Governance: Owner not unique"); isOwner[ownersChange.ownerChanged] = true; owners.push(ownersChange.ownerChanged); } else { require(isOwner[ownersChange.ownerChanged], "Governance: Owner not found"); isOwner[ownersChange.ownerChanged] = false; uint256 index; for (uint256 i; i < owners.length; i++) { if (owners[i] == ownersChange.ownerChanged) { index = i; break; } } owners[index] = owners[owners.length - 1]; owners.pop(); if (minConfirmationsRequired > owners.length) { minConfirmationsRequired = owners.length; } } _resetProposals(); emit ExecuteOwnersChange(msg.sender, _ownersChangeIndex); } /** * Creates a proposal for a change in the minimum number of confirmations required to execute * transactions, changes in owners and changes in minum number of confirmations. * `_newValue`: new value for the minimum number of confirmations required */ function proposeMinConfirmationsChange(uint256 _newValue) external onlyOwner { uint256 minConfirmationsChangeIndex = minConfirmationsChanges.length; minConfirmationsChanges.push( MinConfirmationsChange({ newValue: _newValue, numConfirmations: 0 }) ); approveMinConfirmationsChange(minConfirmationsChangeIndex); emit ProposeMinConfirmationsChange(msg.sender, minConfirmationsChangeIndex, _newValue); } /** * Approves a change in the minimum number of confirmations required. */ function approveMinConfirmationsChange(uint256 _minConfirmationsChangeIndex) public onlyOwner minConfirmationsChangeExists(_minConfirmationsChangeIndex) { require( !minConfirmationsChangeApproved[_minConfirmationsChangeIndex][msg.sender], "Governance: Min confirmations change already approved" ); MinConfirmationsChange storage minConfirmationsChange = minConfirmationsChanges[ _minConfirmationsChangeIndex ]; minConfirmationsChange.numConfirmations++; minConfirmationsChangeApproved[_minConfirmationsChangeIndex][msg.sender] = true; } /** * Executes a change in the minimum number of confirmations required. * It should have the minimum number of confirmations required in order to be executed. */ function executeMinConfirmationsChange(uint256 _minConfirmationsChangeIndex) public onlyOwner minConfirmationsChangeExists(_minConfirmationsChangeIndex) { MinConfirmationsChange storage minConfirmationsChange = minConfirmationsChanges[ _minConfirmationsChangeIndex ]; require( minConfirmationsChange.numConfirmations >= minConfirmationsRequired, "Governance: Min confirmations change not approved" ); require( minConfirmationsChange.newValue > 0 && minConfirmationsChange.newValue <= owners.length, "Governance: Invalid minimum confirmations" ); minConfirmationsRequired = minConfirmationsChange.newValue; _resetProposals(); emit ExecuteMinConfirmationsChange(msg.sender, _minConfirmationsChangeIndex); } /** * Resets all proposals confirmations count after the owners list or the * minConfirmationsRequired value have been modified. * Existing approvals for those proposals are invalidated. */ function _resetProposals() private { for (uint256 i; i < transactions.length; i++) { if (!transactions[i].executed) { transactions[i].numConfirmations = 0; } } for (uint256 i; i < ownersChanges.length; i++) { ownersChanges[i].numConfirmations = 0; } for (uint256 i; i < minConfirmationsChanges.length; i++) { minConfirmationsChanges[i].numConfirmations = 0; } } }
Returns total number of minimum confirmations change proposals./
function minConfirmationsChangesCount() external view returns (uint256) { return minConfirmationsChanges.length; }
12,720,701
pragma solidity 0.6.12; //---------------------------------------------------------------------------------- // I n s t a n t // // .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo. // .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo. // .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO: // .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO' // 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO' // //---------------------------------------------------------------------------------- // // Chef Gonpachi's Post Auction Launcher // // A post auction contract that takes the proceeds and creates a liquidity pool // // // 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 // // 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. // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // Made for Sushi.com // // Enjoy. (c) Chef Gonpachi // <https://github.com/chefgonpachi/MISO/> // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0 // --------------------------------------------------------------------- import "../OpenZeppelin/utils/ReentrancyGuard.sol"; import "../Access/MISOAccessControls.sol"; import "../Utils/SafeTransfer.sol"; import "../Utils/BoringMath.sol"; import "../UniswapV2/UniswapV2Library.sol"; import "../UniswapV2/interfaces/IUniswapV2Pair.sol"; import "../UniswapV2/interfaces/IUniswapV2Factory.sol"; import "../interfaces/IWETH9.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IMisoAuction.sol"; contract PostAuctionLauncher is MISOAccessControls, SafeTransfer, ReentrancyGuard { using BoringMath for uint256; using BoringMath128 for uint128; using BoringMath64 for uint64; using BoringMath32 for uint32; using BoringMath16 for uint16; address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 private constant LIQUIDITY_PRECISION = 10000; /// @notice MISOLiquidity template id. uint256 public constant liquidityTemplate = 3; /// @notice First Token address. IERC20 public token1; /// @notice Second Token address. IERC20 public token2; /// @notice Uniswap V2 factory address. IUniswapV2Factory public factory; /// @notice WETH contract address. address private immutable weth; /// @notice LP pair address. address public tokenPair; /// @notice Withdraw wallet address. address public wallet; /// @notice Token market contract address. IMisoAuction public market; struct LauncherInfo { uint32 locktime; uint64 unlock; uint16 liquidityPercent; bool launched; uint128 liquidityAdded; } LauncherInfo public launcherInfo; /// @notice Emitted when LP contract is initialised. event InitLiquidityLauncher(address indexed token1, address indexed token2, address factory, address sender); /// @notice Emitted when LP is launched. event LiquidityAdded(uint256 liquidity); /// @notice Emitted when wallet is updated. event WalletUpdated(address indexed wallet); /// @notice Emitted when launcher is cancelled. event LauncherCancelled(address indexed wallet); constructor (address _weth) public { weth = _weth; } /** * @notice Initializes main contract variables (requires launchwindow to be more than 2 days.) * @param _market Auction address for launcher. * @param _factory Uniswap V2 factory address. * @param _admin Contract owner address. * @param _wallet Withdraw wallet address. * @param _liquidityPercent Percentage of payment currency sent to liquidity pool. * @param _locktime How long the liquidity will be locked. Number of seconds. */ function initAuctionLauncher( address _market, address _factory, address _admin, address _wallet, uint256 _liquidityPercent, uint256 _locktime ) public { require(_locktime < 10000000000, 'PostAuction: Enter an unix timestamp in seconds, not miliseconds'); require(_liquidityPercent <= LIQUIDITY_PRECISION, 'PostAuction: Liquidity percentage greater than 100.00% (>10000)'); require(_liquidityPercent > 0, 'PostAuction: Liquidity percentage equals zero'); require(_admin != address(0), "PostAuction: admin is the zero address"); require(_wallet != address(0), "PostAuction: wallet is the zero address"); initAccessControls(_admin); market = IMisoAuction(_market); token1 = IERC20(market.paymentCurrency()); token2 = IERC20(market.auctionToken()); if (address(token1) == ETH_ADDRESS) { token1 = IERC20(weth); } uint256 d1 = uint256(token1.decimals()); uint256 d2 = uint256(token2.decimals()); require(d2 >= d1); factory = IUniswapV2Factory(_factory); bytes32 pairCodeHash = IUniswapV2Factory(_factory).pairCodeHash(); tokenPair = UniswapV2Library.pairFor(_factory, address(token1), address(token2), pairCodeHash); wallet = _wallet; launcherInfo.liquidityPercent = BoringMath.to16(_liquidityPercent); launcherInfo.locktime = BoringMath.to32(_locktime); uint256 initalTokenAmount = market.getTotalTokens().mul(_liquidityPercent).div(LIQUIDITY_PRECISION); _safeTransferFrom(address(token2), msg.sender, initalTokenAmount); emit InitLiquidityLauncher(address(token1), address(token2), address(_factory), _admin); } receive() external payable { if(msg.sender != weth ){ depositETH(); } } /// @notice Deposits ETH to the contract. function depositETH() public payable { require(address(token1) == weth || address(token2) == weth, "PostAuction: Launcher not accepting ETH"); if (msg.value > 0 ) { IWETH(weth).deposit{value : msg.value}(); } } /** * @notice Deposits first Token to the contract. * @param _amount Number of tokens to deposit. */ function depositToken1(uint256 _amount) external returns (bool success) { return _deposit( address(token1), msg.sender, _amount); } /** * @notice Deposits second Token to the contract. * @param _amount Number of tokens to deposit. */ function depositToken2(uint256 _amount) external returns (bool success) { return _deposit( address(token2), msg.sender, _amount); } /** * @notice Deposits Tokens to the contract. * @param _amount Number of tokens to deposit. * @param _from Where the tokens to deposit will come from. * @param _token Token address. */ function _deposit(address _token, address _from, uint _amount) internal returns (bool success) { require(!launcherInfo.launched, "PostAuction: Must first launch liquidity"); require(launcherInfo.liquidityAdded == 0, "PostAuction: Liquidity already added"); require(_amount > 0, "PostAuction: Token amount must be greater than 0"); _safeTransferFrom(_token, _from, _amount); return true; } /** * @notice Checks if market wallet is set to this launcher */ function marketConnected() public view returns (bool) { return market.wallet() == address(this); } /** * @notice Finalizes Token sale and launches LP. * @return liquidity Number of LPs. */ function finalize() external nonReentrant returns (uint256 liquidity) { // GP: Can we remove admin, let anyone can finalise and launch? // require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator"); require(marketConnected(), "PostAuction: Auction must have this launcher address set as the destination wallet"); require(!launcherInfo.launched); if (!market.finalized()) { market.finalize(); } launcherInfo.launched = true; if (!market.auctionSuccessful() ) { return 0; } /// @dev if the auction is settled in weth, wrap any contract balance uint256 launcherBalance = address(this).balance; if (launcherBalance > 0 ) { IWETH(weth).deposit{value : launcherBalance}(); } (uint256 token1Amount, uint256 token2Amount) = getTokenAmounts(); /// @dev cannot start a liquidity pool with no tokens on either side if (token1Amount == 0 || token2Amount == 0 ) { return 0; } address pair = factory.getPair(address(token1), address(token2)); require(pair == address(0) || getLPBalance() == 0, "PostLiquidity: Pair not new"); if(pair == address(0)) { createPool(); } /// @dev add liquidity to pool via the pair directly _safeTransfer(address(token1), tokenPair, token1Amount); _safeTransfer(address(token2), tokenPair, token2Amount); liquidity = IUniswapV2Pair(tokenPair).mint(address(this)); launcherInfo.liquidityAdded = BoringMath.to128(uint256(launcherInfo.liquidityAdded).add(liquidity)); /// @dev if unlock time not yet set, add it. if (launcherInfo.unlock == 0 ) { launcherInfo.unlock = BoringMath.to64(block.timestamp + uint256(launcherInfo.locktime)); } emit LiquidityAdded(liquidity); } function getTokenAmounts() public view returns (uint256 token1Amount, uint256 token2Amount) { token1Amount = getToken1Balance().mul(uint256(launcherInfo.liquidityPercent)).div(LIQUIDITY_PRECISION); token2Amount = getToken2Balance(); uint256 tokenPrice = market.tokenPrice(); uint256 d2 = uint256(token2.decimals()); uint256 maxToken1Amount = token2Amount.mul(tokenPrice).div(10**(d2)); uint256 maxToken2Amount = token1Amount .mul(10**(d2)) .div(tokenPrice); /// @dev if more than the max. if (token2Amount > maxToken2Amount) { token2Amount = maxToken2Amount; } /// @dev if more than the max. if (token1Amount > maxToken1Amount) { token1Amount = maxToken1Amount; } } /** * @notice Withdraws LPs from the contract. * @return liquidity Number of LPs. */ function withdrawLPTokens() external returns (uint256 liquidity) { require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator"); require(launcherInfo.launched, "PostAuction: Must first launch liquidity"); require(block.timestamp >= uint256(launcherInfo.unlock), "PostAuction: Liquidity is locked"); liquidity = IERC20(tokenPair).balanceOf(address(this)); require(liquidity > 0, "PostAuction: Liquidity must be greater than 0"); _safeTransfer(tokenPair, wallet, liquidity); } /// @notice Withraws deposited tokens and ETH from the contract to wallet. function withdrawDeposits() external { require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator"); require(launcherInfo.launched, "PostAuction: Must first launch liquidity"); uint256 token1Amount = getToken1Balance(); if (token1Amount > 0 ) { _safeTransfer(address(token1), wallet, token1Amount); } uint256 token2Amount = getToken2Balance(); if (token2Amount > 0 ) { _safeTransfer(address(token2), wallet, token2Amount); } } // TODO // GP: Sweep non relevant ERC20s / ETH //-------------------------------------------------------- // Setter functions //-------------------------------------------------------- /** * @notice Admin can set the wallet through this function. * @param _wallet Wallet is where funds will be sent. */ function setWallet(address payable _wallet) external { require(hasAdminRole(msg.sender)); require(_wallet != address(0), "Wallet is the zero address"); wallet = _wallet; emit WalletUpdated(_wallet); } function cancelLauncher() external { require(hasAdminRole(msg.sender)); require(!launcherInfo.launched); launcherInfo.launched = true; emit LauncherCancelled(msg.sender); } //-------------------------------------------------------- // Helper functions //-------------------------------------------------------- /** * @notice Creates new SLP pair through SushiSwap. */ function createPool() internal { factory.createPair(address(token1), address(token2)); } //-------------------------------------------------------- // Getter functions //-------------------------------------------------------- /** * @notice Gets the number of first token deposited into this contract. * @return uint256 Number of WETH. */ function getToken1Balance() public view returns (uint256) { return token1.balanceOf(address(this)); } /** * @notice Gets the number of second token deposited into this contract. * @return uint256 Number of WETH. */ function getToken2Balance() public view returns (uint256) { return token2.balanceOf(address(this)); } /** * @notice Returns LP token address.. * @return address LP address. */ function getLPTokenAddress() public view returns (address) { return tokenPair; } /** * @notice Returns LP Token balance. * @return uint256 LP Token balance. */ function getLPBalance() public view returns (uint256) { return IERC20(tokenPair).balanceOf(address(this)); } //-------------------------------------------------------- // Init functions //-------------------------------------------------------- /** * @notice Decodes and hands auction data to the initAuction function. * @param _data Encoded data for initialization. */ function init(bytes calldata _data) external payable { } function initLauncher( bytes calldata _data ) public { ( address _market, address _factory, address _admin, address _wallet, uint256 _liquidityPercent, uint256 _locktime ) = abi.decode(_data, ( address, address, address, address, uint256, uint256 )); initAuctionLauncher( _market, _factory,_admin,_wallet,_liquidityPercent,_locktime); } /** * @notice Collects data to initialize the auction and encodes them. * @param _market Auction address for launcher. * @param _factory Uniswap V2 factory address. * @param _admin Contract owner address. * @param _wallet Withdraw wallet address. * @param _liquidityPercent Percentage of payment currency sent to liquidity pool. * @param _locktime How long the liquidity will be locked. Number of seconds. * @return _data All the data in bytes format. */ function getLauncherInitData( address _market, address _factory, address _admin, address _wallet, uint256 _liquidityPercent, uint256 _locktime ) external pure returns (bytes memory _data) { return abi.encode(_market, _factory, _admin, _wallet, _liquidityPercent, _locktime ); } } pragma solidity 0.6.12; /** * @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 () internal { _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: GPL-3.0-only pragma solidity 0.6.12; import "./MISOAdminAccess.sol"; /** * @notice Access Controls * @author Attr: BlockRocket.tech */ contract MISOAccessControls is MISOAdminAccess { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) public view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) public view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Used to check whether an address has the operator role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasOperatorRole(address _address) public view returns (bool) { return hasRole(OPERATOR_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Grants the operator role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addOperatorRole(address _address) external { grantRole(OPERATOR_ROLE, _address); } /** * @notice Removes the operator role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeOperatorRole(address _address) external { revokeRole(OPERATOR_ROLE, _address); } } pragma solidity 0.6.12; contract SafeTransfer { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Event for token withdrawals. event TokensWithdrawn(address token, address to, uint256 amount); /// @dev Helper function to handle both ETH and ERC20 payments function _safeTokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _safeTransferETH(_to,_amount ); } else { _safeTransfer(_token, _to, _amount); } emit TokensWithdrawn(_token, _to, _amount); } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { _safeTransfer(_token, _to, _amount); } emit TokensWithdrawn(_token, _to, _amount); } /// @dev Transfer helper from UniswapV2 Router function _safeApprove(address token, address to, uint 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: APPROVE_FAILED'); } /** * There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 * Im trying to make it a habit to put external calls last (reentrancy) * You can put this in an internal function if you like. */ function _safeTransfer( address token, address to, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)")) abi.encodeWithSelector(0xa9059cbb, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed } function _safeTransferFrom( address token, address from, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed } function _safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function _safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "BoringMath: Div zero"); c = a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to16(uint256 a) internal pure returns (uint16 c) { require(a <= uint16(-1), "BoringMath: uint16 Overflow"); c = uint16(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath16 { function add(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } pragma solidity 0.6.12; import './interfaces/IUniswapV2Pair.sol'; import "./libraries/SafeMath.sol"; library UniswapV2Library { using SafeMathUniswap for uint; // 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, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).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, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(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, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(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, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path, bytes32 pairCodeHash) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: 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], pairCodeHash); 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, bytes32 pairCodeHash) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: 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], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } pragma solidity 0.6.12; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity 0.6.12; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function pairCodeHash() external pure returns (bytes32); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } pragma solidity 0.6.12; import "./IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint) external; function transfer(address, uint) external returns (bool); } pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transferFrom( address from, address to, uint256 amount ) external returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } pragma solidity 0.6.12; interface IMisoAuction { function initAuction( address _funder, address _token, uint256 _tokenSupply, uint256 _startDate, uint256 _endDate, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address _operator, address _pointList, address payable _wallet ) external; function auctionSuccessful() external view returns (bool); function finalized() external view returns (bool); function wallet() external view returns (address); function paymentCurrency() external view returns (address); function auctionToken() external view returns (address); function finalize() external; function tokenPrice() external view returns (uint256); function getTotalTokens() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.6.12; import "../OpenZeppelin/access/AccessControl.sol"; contract MISOAdminAccess is AccessControl { /// @dev Whether access is initialised. bool private initAccess; /// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses. constructor() public { } /** * @notice Initializes access controls. * @param _admin Admins address. */ function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); require(_admin != address(0), "Incorrect input"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role. * @param _address EOA or contract being checked. * @return bool True if the account has the role or false if it does not. */ function hasAdminRole(address _address) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address. * @dev The sender must have the admin role. * @param _address EOA or contract receiving the new role. */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Removes the admin role from an address. * @dev The sender must have the admin role. * @param _address EOA or contract affected. */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); } } pragma solidity 0.6.12; import "../utils/EnumerableSet.sol"; import "../utils/Context.sol"; /** * @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; 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()); } } } pragma solidity 0.6.12; /** * @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; // 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]; } // 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)); } } pragma solidity 0.6.12; /* * @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; } } pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
Gets the number of second token deposited into this contract. return uint256 Number of WETH./
function getToken2Balance() public view returns (uint256) { return token2.balanceOf(address(this)); }
82,035
pragma solidity ^0.5.2; pragma experimental ABIEncoderV2; import "../Core/Core.sol"; /** * @title STF * @notice Contains all state transition functions (STFs) currently used by all Engines */ contract STF is Core { /** * State transition for PAM analysis events * @param state the old state * @return the new state */ function STF_PAM_AD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.statusDate = scheduleTime; return state; } /** * State transition for PAM fee payment events * @param state the old state * @return the new state */ function STF_PAM_FP ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = 0; state.statusDate = scheduleTime; return state; } /** * State transition for PAM initial exchange * @param state the old state * @return the new state */ function STF_PAM_IED ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.notionalPrincipal = roleSign(terms.contractRole) * terms.notionalPrincipal; state.nominalInterestRate = terms.nominalInterestRate; state.statusDate = scheduleTime; state.accruedInterest = terms.accruedInterest; // if (terms.cycleAnchorDateOfInterestPayment != 0 && // terms.cycleAnchorDateOfInterestPayment < terms.initialExchangeDate // ) { // state.accruedInterest = state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult( // yearFraction( // terms.cycleAnchorDateOfInterestPayment, // scheduleTime, // terms.dayCountConvention, // terms.maturityDate // ) // ); // } return state; } /** * State transition for PAM interest capitalization * @param state the old state * @return the new state */ function STF_PAM_IPCI ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.notionalPrincipal = state.notionalPrincipal .add( state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ) ); state.accruedInterest = 0; state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.statusDate = scheduleTime; return state; } /** * State transition for PAM interest payment * @param state the old state * @return the new state */ function STF_PAM_IP ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = 0; state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.statusDate = scheduleTime; return state; } /** * State transition for PAM principal prepayment * @param state the old state * @return the new state */ function STF_PAM_PP ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.notionalPrincipal -= 0; // riskFactor(terms.objectCodeOfPrepaymentModel, scheduleTime, state, terms) * state.notionalPrincipal; state.statusDate = scheduleTime; return state; } /** * State transition for PAM principal redemption * @param state the old state * @return the new state */ function STF_PAM_PR ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.notionalPrincipal = 0; state.statusDate = scheduleTime; return state; } /** * State transition for PAM penalty payments * @param state the old state * @return the new state */ function STF_PAM_PY ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.statusDate = scheduleTime; return state; } /** * State transition for PAM fixed rate resets * @param state the old state * @return the new state */ function STF_PAM_RRF ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.nominalInterestRate = terms.nextResetRate; state.statusDate = scheduleTime; return state; } /** * State transition for PAM variable rate resets * @param state the old state * @return the new state */ function STF_PAM_RR ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { // int256 rate = //riskFactor(terms.marketObjectCodeOfRateReset, scheduleTime, state, terms) // * terms.rateMultiplier + terms.rateSpread; // apply external rate, multiply with rateMultiplier and add the spread int256 rate = int256(uint256(externalData)).floatMult(terms.rateMultiplier).add(terms.rateSpread); // deltaRate is the difference between the rate that includes external data, spread and multiplier and the currently active rate from the state int256 deltaRate = rate.sub(state.nominalInterestRate); // apply period cap/floor // the deltaRate (the interest rate change) cannot be bigger than the period cap // and not smaller than the period floor // math: deltaRate = min(max(deltaRate, periodFloor),lifeCap) deltaRate = deltaRate.max(terms.periodFloor).min(terms.periodCap); rate = state.nominalInterestRate.add(deltaRate); // apply life cap/floor // the rate cannot be higher than the lifeCap // and not smaller than the lifeFloor // math: rate = min(max(rate,lifeFloor),lifeCap) rate = rate.max(terms.lifeFloor).min(terms.lifeCap); int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.nominalInterestRate = rate; state.statusDate = scheduleTime; return state; } /** * State transition for PAM scaling index revision events * @param state the old state * @return the new state */ function STF_PAM_SC ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); if ((terms.scalingEffect == ScalingEffect.I00) || (terms.scalingEffect == ScalingEffect.IN0) || (terms.scalingEffect == ScalingEffect.I0M) || (terms.scalingEffect == ScalingEffect.INM) ) { state.interestScalingMultiplier = 0; // riskFactor(terms.marketObjectCodeOfScalingIndex, scheduleTime, state, terms) } if ((terms.scalingEffect == ScalingEffect._0N0) || (terms.scalingEffect == ScalingEffect._0NM) || (terms.scalingEffect == ScalingEffect.IN0) || (terms.scalingEffect == ScalingEffect.INM) ) { state.notionalScalingMultiplier = 0; // riskFactor(terms.marketObjectCodeOfScalingIndex, scheduleTime, state, terms) } state.statusDate = scheduleTime; return state; } /** * State transition for PAM termination events * @param state the old state * @return the new state */ function STF_PAM_TD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.notionalPrincipal = 0; state.accruedInterest = 0; state.feeAccrued = 0; state.statusDate = scheduleTime; return state; } /** * State transition for PAM credit events * @param state the old state * @return the new state */ function STF_PAM_CE ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns(State memory) { uint256 nonPerformingDate = (state.nonPerformingDate == 0) ? shiftEventTime(scheduleTime, terms.businessDayConvention, terms.calendar) : state.nonPerformingDate; uint256 currentTimestamp = uint256(externalData); bool isInGracePeriod = false; if (terms.gracePeriod.isSet) { uint256 graceDate = getTimestampPlusPeriod(terms.gracePeriod, nonPerformingDate); if (currentTimestamp <= graceDate) { state.contractPerformance = ContractPerformance.DL; isInGracePeriod = true; } } if (terms.delinquencyPeriod.isSet && !isInGracePeriod) { uint256 delinquencyDate = getTimestampPlusPeriod(terms.delinquencyPeriod, nonPerformingDate); if (currentTimestamp <= delinquencyDate) { state.contractPerformance = ContractPerformance.DQ; } else { state.contractPerformance = ContractPerformance.DF; } } if (state.nonPerformingDate == 0) { state.nonPerformingDate = shiftEventTime( scheduleTime, terms.businessDayConvention, terms.calendar ); } return state; } // function STF_ANN_AD ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.nominalAccrued = state.nominalAccrued // .add( // state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.feeAccrued = state.feeAccrued // .add( // terms.feeRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.statusDate = scheduleTime; // return state; // } // function STF_ANN_CD ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.nominalAccrued = state.nominalAccrued // .add( // state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.feeAccrued = state.feeAccrued // .add( // terms.feeRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.ContractPerformance = ContractPerformance.DF; // state.statusDate = scheduleTime; // return state; // } // function STF_ANN_FP ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.nominalAccrued = state.nominalAccrued // .add( // state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.feeAccrued = 0; // state.statusDate = scheduleTime; // return state; // } function STF_ANN_IED ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.notionalPrincipal = roleSign(terms.contractRole) * terms.notionalPrincipal; state.nominalInterestRate = terms.nominalInterestRate; state.statusDate = scheduleTime; state.accruedInterest = terms.accruedInterest; // if (terms.cycleAnchorDateOfInterestPayment != 0 && // terms.cycleAnchorDateOfInterestPayment < terms.initialExchangeDate // ) { // state.accruedInterest = state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult( // yearFraction( // shiftCalcTime(terms.cycleAnchorDateOfInterestPayment, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ) // ); // } return state; } function STF_ANN_IPCI ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ) ); state.accruedInterest = 0; state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.statusDate = scheduleTime; return state; } function STF_ANN_IP ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = 0; state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.statusDate = scheduleTime; return state; } // function STF_ANN_PP ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.nominalAccrued = state.nominalAccrued // .add( // state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.feeAccrued = state.feeAccrued // .add( // terms.feeRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.notionalPrincipal -= 0; // riskFactor(terms.objectCodeOfPrepaymentModel, scheduleTime, state, terms) * state.notionalPrincipal; // state.statusDate = scheduleTime; // return state; // } function STF_ANN_PR ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.notionalPrincipal = state.notionalPrincipal .sub( roleSign(terms.contractRole) * ( roleSign(terms.contractRole) * state.notionalPrincipal ) .min( roleSign(terms.contractRole) * ( state.nextPrincipalRedemptionPayment .sub(state.accruedInterest) ) ) ); state.statusDate = scheduleTime; return state; } function STF_ANN_MD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.notionalPrincipal = 0.0; state.statusDate = scheduleTime; return state; } // STF_PAM_PY // function STF_ANN_PY ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.nominalAccrued = state.nominalAccrued // .add( // state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.feeAccrued = state.feeAccrued // .add( // terms.feeRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.statusDate = scheduleTime; // return state; // } // function STF_ANN_RRF ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.nominalAccrued = state.nominalAccrued // .add( // state.nominalInterestRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.feeAccrued = state.feeAccrued // .add( // terms.feeRate // .floatMult(state.notionalPrincipal) // .floatMult(timeFromLastEvent) // ); // state.nominalInterestRate = terms.nextResetRate; // state.statusDate = scheduleTime; // return state; // } function STF_ANN_RR ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { // int256 rate = //riskFactor(terms.marketObjectCodeOfRateReset, scheduleTime, state, terms) // * terms.rateMultiplier + terms.rateSpread; int256 rate = int256(externalData) * terms.rateMultiplier + terms.rateSpread; int256 deltaRate = rate.sub(state.nominalInterestRate); // apply period cap/floor if ((terms.lifeCap < deltaRate) && (terms.lifeCap < ((-1) * terms.periodFloor))) { deltaRate = terms.lifeCap; } else if (deltaRate < ((-1) * terms.periodFloor)) { deltaRate = ((-1) * terms.periodFloor); } rate = state.nominalInterestRate.add(deltaRate); // apply life cap/floor if (terms.lifeCap < rate && terms.lifeCap < terms.lifeFloor) { rate = terms.lifeCap; } else if (rate < terms.lifeFloor) { rate = terms.lifeFloor; } int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.nominalInterestRate = rate; state.nextPrincipalRedemptionPayment = 0; // TODO: implement annuity calculator state.statusDate = scheduleTime; return state; } function STF_ANN_SC ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = state.feeAccrued .add( terms.feeRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); if ((terms.scalingEffect == ScalingEffect.I00) || (terms.scalingEffect == ScalingEffect.IN0) || (terms.scalingEffect == ScalingEffect.I0M) || (terms.scalingEffect == ScalingEffect.INM) ) { state.interestScalingMultiplier = 0; // riskFactor(terms.marketObjectCodeOfScalingIndex, scheduleTime, state, terms) } if ((terms.scalingEffect == ScalingEffect._0N0) || (terms.scalingEffect == ScalingEffect._0NM) || (terms.scalingEffect == ScalingEffect.IN0) || (terms.scalingEffect == ScalingEffect.INM) ) { state.notionalScalingMultiplier = 0; // riskFactor(terms.marketObjectCodeOfScalingIndex, scheduleTime, state, terms) } state.statusDate = scheduleTime; return state; } // function STF_ANN_TD ( // uint256 scheduleTime, // LifecycleTerms memory terms, // State memory state // ) // internal // pure // returns (State memory) // { // int256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); // state.notionalPrincipal = 0; // state.nominalAccrued = 0; // state.feeAccrued = 0; // state.statusDate = scheduleTime; // return state; // } function STF_CEG_MD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { state.notionalPrincipal = 0; state.statusDate = scheduleTime; return state; } function STF_CEG_XD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { state.statusDate = scheduleTime; // decode state.notionalPrincipal of underlying from externalData state.executionAmount = terms.coverageOfCreditEnhancement.floatMult(int256(externalData)); state.executionDate = scheduleTime; if (terms.feeBasis == FeeBasis.A) { state.feeAccrued = roleSign(terms.contractRole) * terms.feeRate; } else { state.feeAccrued = state.feeAccrued .add( yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ) .floatMult(terms.feeRate) .floatMult(state.notionalPrincipal) ); } return state; } function STF_CEG_STD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { state.statusDate = scheduleTime; state.notionalPrincipal = 0; state.feeAccrued = 0; return state; } function STF_CEG_PRD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { state.notionalPrincipal = roleSign(terms.contractRole) * terms.notionalPrincipal; state.nominalInterestRate = terms.feeRate; state.statusDate = scheduleTime; return state; } function STF_CEG_FP ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { // uint256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); state.feeAccrued = 0; state.statusDate = scheduleTime; return state; } function STF_CEG_TD ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { // uint256 timeFromLastEvent = yearFraction( // shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), // shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), // terms.dayCountConvention, // terms.maturityDate // ); state.notionalPrincipal = 0; state.accruedInterest = 0; state.feeAccrued = 0; state.statusDate = scheduleTime; return state; } }
State transition for PAM fee payment events state the old state return the new state/
function STF_PAM_FP ( LifecycleTerms memory terms, State memory state, uint256 scheduleTime, bytes32 externalData ) internal pure returns (State memory) { int256 timeFromLastEvent = yearFraction( shiftCalcTime(state.statusDate, terms.businessDayConvention, terms.calendar), shiftCalcTime(scheduleTime, terms.businessDayConvention, terms.calendar), terms.dayCountConvention, terms.maturityDate ); state.accruedInterest = state.accruedInterest .add( state.nominalInterestRate .floatMult(state.notionalPrincipal) .floatMult(timeFromLastEvent) ); state.feeAccrued = 0; state.statusDate = scheduleTime; return state; }
12,940,266
/** *Submitted for verification at Etherscan.io on 2022-04-07 */ /* quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack quackQuackQuackquackquackQuackquackQuackquackQuackQuackquackquackQuackquackQuack */ // 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) { // Insred 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 (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/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); } } } } // 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/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 (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 (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; } pragma solidity ^0.8.0; interface IERC721Batch { function isOwnerOf( address account, uint[] calldata tokenIds ) external view returns( bool ); function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external; function walletOfOwner( address account ) external view returns( uint[] memory ); } // 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 (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); } } pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ abstract contract QQ721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; struct Token{ address owner; } mapping(address => uint) balances; Token[] public tokens; string private _name; string private _symbol; mapping(uint => address) internal _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_){ _name = name_; _symbol = symbol_; } //public view function balanceOf(address owner) public view override returns (uint balance){ return balances[owner]; } function name() external view override returns( string memory name_ ){ return _name; } function ownerOf(uint tokenId) public view override returns( address owner ){ require(_exists(tokenId), "QQ721: query for nonexistent token"); return tokens[tokenId].owner; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns( bool isSupported ){ return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function symbol() external view override returns( string memory symbol_ ){ return _symbol; } //approvals function approve(address to, uint tokenId) external override { address owner = ownerOf(tokenId); require(to != owner, "QQ721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "QQ721: caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint tokenId) public view override returns( address approver ){ require(_exists(tokenId), "QQ721: query for nonexistent token"); return _tokenApprovals[tokenId]; } function isApprovedForAll(address owner, address operator) public view override returns( bool isApproved ){ return _operatorApprovals[owner][operator]; } function setApprovalForAll(address operator, bool approved) external override { _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } //transfers function safeTransferFrom(address from, address to, uint tokenId) external override{ safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint tokenId, bytes memory _data) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "QQ721: caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function transferFrom(address from, address to, uint tokenId) external override { require(_isApprovedOrOwner(_msgSender(), tokenId), "QQ721: caller is not owner nor approved"); _transfer(from, to, tokenId); } //internal function _approve(address to, uint tokenId) internal{ _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer(address from, address to, uint tokenId) internal virtual { if( from != address(0) ) --balances[from]; if( to != address(0) ) ++balances[to]; } function _checkOnERC721Received(address from, address to, uint 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("QQ721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _exists(uint tokenId) internal view returns ( bool ){ return tokenId < tokens.length && tokens[tokenId].owner != address(0); } function _isApprovedOrOwner(address spender, uint tokenId) internal view returns( bool ){ require(_exists(tokenId), "QQ721: query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeTransfer(address from, address to, uint tokenId, bytes memory _data) internal{ _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "QQ721: transfer to non ERC721Receiver implementer"); } function _transfer(address from, address to, uint tokenId) internal { require(ownerOf(tokenId) == from, "QQ721: transfer of token that is not own"); _beforeTokenTransfer( from, to, tokenId ); // Clear approvals from the previous owner _approve(address(0), tokenId); tokens[tokenId].owner = to; emit Transfer(from, to, tokenId); } } pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-GB721 provides low-gas * * mints + transfers * ****************************************/ abstract contract QQ721Enumerable is QQ721, IERC721Enumerable { function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, QQ721) returns( bool isSupported ){ return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint index) external view override returns( uint tokenId ){ uint count; for( uint i; i < tokens.length; ++i ){ if( owner == tokens[i].owner ){ if( count == index ) return i; else ++count; } } revert( "QQ721Enumerable: owner index out of bounds" ); } function tokenByIndex(uint index) external view override returns( uint tokenId ){ require(index < tokens.length, "QQ721Enumerable: query for nonexistent token"); return index; } } pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-GB721 provides low-gas * * mints + transfers * ****************************************/ abstract contract QQ721Batch is QQ721Enumerable, IERC721Batch { function isOwnerOf( address account, uint[] calldata tokenIds ) external view override returns( bool ){ for(uint i; i < tokenIds.length; ++i ){ if( account != tokens[ tokenIds[i] ].owner ) return false; } return true; } function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external override{ for(uint i; i < tokenIds.length; ++i ){ safeTransferFrom( from, to, tokenIds[i], data ); } } function walletOfOwner( address account ) public view override returns( uint[] memory wallet_ ){ uint count; uint quantity = balanceOf( account ); uint[] memory wallet = new uint[]( quantity ); for( uint i; i < tokens.length; ++i ){ if( account == tokens[i].owner ){ wallet[ count++ ] = i; if( count == quantity ) break; } } return wallet; } } pragma solidity ^0.8.0; contract QuackQuack is QQ721Batch, Ownable { using Strings for uint256; uint public constant PRICE = 0.01 ether; uint public constant MAX_ORDER = 69; uint public constant MAX_SUPPLY = 2222; uint public constant TEAM_SUPPLY = 20; bool public teamMinted = false; uint public burned; bool public isSaleActive = false; bool public revealed = false; string private _baseURI; string private constant TOKENURISUFFIX = ".json"; constructor() QQ721("Quack Quack", "QUACK") { } //view: IERC721Metadata function tokenURI( uint tokenId ) external view override returns( string memory ){ require(_exists(tokenId), "query for nonexistent token"); if(!revealed) return _baseURI; return string(abi.encodePacked(_baseURI, tokenId.toString(), TOKENURISUFFIX)); } //view: IERC721Enumerable function totalSupply() public view override returns( uint totalSupply_ ){ return tokens.length - burned; } //payable function mint( uint quantity) external payable { require(isSaleActive, "sale is not active"); require(quantity <= MAX_ORDER, "order too big"); uint fee = PRICE * quantity; require(fee <= msg.value, "fee too low"); unchecked{ for(uint i; i < quantity; ++i){ _mint( msg.sender, tokens.length ); } } } //onlyOwner function teamMint() external onlyOwner{ require(!teamMinted, "team already minted"); unchecked{ for(uint i; i < TEAM_SUPPLY; ++i){ _mint( msg.sender, tokens.length ); } teamMinted = true; } } function burnFrom( address account, uint[] calldata tokenIds ) external onlyOwner{ unchecked{ for(uint i; i < tokenIds.length; ++i ){ _burn( account, tokenIds[i] ); } } } function mintTo(address[] calldata accounts, uint[] calldata quantity ) external payable onlyOwner{ require(quantity.length == accounts.length, "must provide equal quantities and accounts" ); uint totalQuantity; unchecked{ for(uint i; i < quantity.length; ++i){ totalQuantity += quantity[i]; } } uint supply = totalSupply(); require( supply + totalQuantity < MAX_SUPPLY, "mint/order exceeds supply" ); unchecked{ for(uint i; i < accounts.length; ++i){ for(uint j; j < quantity[i]; ++j){ _mint( accounts[i], tokens.length ); } } } } function resurrect( address[] calldata accounts, uint[] calldata tokenIds ) external onlyOwner{ require(tokenIds.length == accounts.length, "must provide equal tokenIds and accounts" ); unchecked{ for(uint i; i < tokenIds.length; ++i ){ _mint( accounts[i], tokenIds[i] ); } } } function setActive() external onlyOwner{ isSaleActive = !isSaleActive; } function setRevealed() external onlyOwner{ revealed = !revealed; } function setBaseURI(string calldata _newBaseURI) external onlyOwner{ _baseURI = _newBaseURI; } function withdraw(address _address) public onlyOwner { uint256 balance = address(this).balance; payable(_address).transfer(balance); } //private function _burn( address from, uint tokenId ) private { require( _exists( tokenId ), "query for nonexistent token" ); require( from == tokens[ tokenId ].owner, "owner mismatch" ); ++burned; _beforeTokenTransfer( from, address(0), tokenId ); tokens[ tokenId ].owner = address(0); emit Transfer(from, address(0), tokenId); } function _mint( address to, uint tokenId ) private { _beforeTokenTransfer( address(0), to, tokenId ); if( tokenId < tokens.length ){ require( !_exists( tokenId ), "can't resurrect existing token" ); --burned; tokens[ tokenId ].owner = to; } else{ tokens.push( Token( to ) ); } emit Transfer(address(0), to, tokenId); } }
Clear approvals from the previous owner
function _transfer(address from, address to, uint tokenId) internal { require(ownerOf(tokenId) == from, "QQ721: transfer of token that is not own"); _beforeTokenTransfer( from, to, tokenId ); _approve(address(0), tokenId); tokens[tokenId].owner = to; emit Transfer(from, to, tokenId); }
15,123,261
pragma solidity 0.4.20; import 'libraries/token/StandardToken.sol'; contract VariableSupplyToken is StandardToken { using SafeMathUint256 for uint256; event Mint(address indexed target, uint256 value); event Burn(address indexed target, uint256 value); /** * @dev mint tokens for a specified address * @param _target The address to mint tokens for. * @param _amount The amount to be minted. */ function mint(address _target, uint256 _amount) internal returns (bool) { balances[_target] = balances[_target].add(_amount); supply = supply.add(_amount); Mint(_target, _amount); onMint(_target, _amount); return true; } /** * @dev burn tokens belonging to a specified address * @param _target The address to burn tokens for. * @param _amount The amount to be burned. */ function burn(address _target, uint256 _amount) internal returns (bool) { balances[_target] = balances[_target].sub(_amount); supply = supply.sub(_amount); Burn(_target, _amount); onBurn(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function onMint(address, uint256) internal returns (bool); // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function onBurn(address, uint256) internal returns (bool); }
burn tokens belonging to a specified address _target The address to burn tokens for. _amount The amount to be burned./
function burn(address _target, uint256 _amount) internal returns (bool) { balances[_target] = balances[_target].sub(_amount); supply = supply.sub(_amount); Burn(_target, _amount); onBurn(_target, _amount); return true; }
897,440
/** * @authors: [@unknownunknown1] * @reviewers: [] * @auditors: [] * @bounties: [] */ pragma solidity ^0.4.24; import "./Arbitrator.sol"; import "./IArbitrable.sol"; import "../../libraries/CappedMath.sol"; contract MultipleArbitrableTransactionWithAppeals is IArbitrable { using CappedMath for uint; // **************************** // // * Contract variables * // // **************************** // uint8 constant AMOUNT_OF_CHOICES = 2; uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. enum Party {None, Sender, Receiver} enum Status {NoDispute, WaitingSender, WaitingReceiver, DisputeCreated, Resolved} struct Transaction { address sender; address receiver; uint amount; uint timeoutPayment; // Time in seconds after which the transaction can be automatically executed if not disputed. uint disputeId; // If dispute exists, the ID of the dispute. uint senderFee; // Total fees paid by the sender. uint receiverFee; // Total fees paid by the receiver. uint lastInteraction; // Last interaction for the dispute procedure. Status status; Round[] rounds; // Tracks each appeal round of a dispute. uint ruling; // The ruling of the dispute, if any. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side in this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } Transaction[] public transactions; bytes public arbitratorExtraData; // Extra data to set up the arbitration. Arbitrator public arbitrator; // Address of the arbitrator contract. uint public feeTimeout; // Time in seconds a party can take to pay arbitration fees before being considered unresponding and lose the dispute. uint public sharedStakeMultiplier; // Multiplier for calculating the appeal fee that must be paid by submitter in the case where there is no winner or loser (e.g. when the arbitrator ruled "refuse to arbitrate"). uint public winnerStakeMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. mapping (uint => uint) public disputeIDtoTransactionID; // One-to-one relationship between the dispute and the transaction. // **************************** // // * Events * // // **************************** // /** @dev To be emitted when a party pays or reimburses the other. * @param _transactionID The index of the transaction. * @param _amount The amount paid. * @param _party The party that paid. */ event Payment(uint indexed _transactionID, uint _amount, address _party); /** @dev Indicate that a party has to pay a fee or would otherwise be considered as losing. * @param _transactionID The index of the transaction. * @param _party The party who has to pay. */ event HasToPayFee(uint indexed _transactionID, Party _party); /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Emitted when a transaction is created. * @param _transactionID The index of the transaction. * @param _sender The address of the sender. * @param _receiver The address of the receiver. * @param _amount The initial amount in the transaction. */ event TransactionCreated(uint _transactionID, address indexed _sender, address indexed _receiver, uint _amount); /** @dev To be emitted when the appeal fees of one of the parties are fully funded. * @param _transactionID The ID of the respective transaction. * @param _party The party that is fully funded. */ event HasPaidAppealFee(uint indexed _transactionID, Party _party); // **************************** // // * Arbitrable functions * // // * Modifying the state * // // **************************** // /** @dev Constructor. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. * @param _feeTimeout Arbitration fee timeout for the parties. * @param _sharedStakeMultiplier Multiplier of the appeal cost that submitter must pay for a round when there is no winner/loser in the previous round. In basis points. * @param _winnerStakeMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points. * @param _loserStakeMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points. */ constructor ( Arbitrator _arbitrator, bytes _arbitratorExtraData, uint _feeTimeout, uint _sharedStakeMultiplier, uint _winnerStakeMultiplier, uint _loserStakeMultiplier ) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; feeTimeout = _feeTimeout; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Create a transaction. * @param _timeoutPayment Time after which a party can automatically execute the arbitrable transaction. * @param _receiver The recipient of the transaction. * @param _metaEvidence Link to the meta-evidence. * @return transactionID The index of the transaction. */ function createTransaction( uint _timeoutPayment, address _receiver, string _metaEvidence ) public payable returns (uint transactionID) { transactionID = transactions.length++; Transaction storage transaction = transactions[transactionID]; transaction.sender = msg.sender; transaction.receiver = _receiver; transaction.amount = msg.value; transaction.timeoutPayment = _timeoutPayment; transaction.lastInteraction = now; emit MetaEvidence(transactionID, _metaEvidence); emit TransactionCreated(transactionID, msg.sender, _receiver, msg.value); } /** @dev Pay receiver. To be called if the good or service is provided. * @param _transactionID The index of the transaction. * @param _amount Amount to pay in wei. */ function pay(uint _transactionID, uint _amount) public { Transaction storage transaction = transactions[_transactionID]; require(transaction.sender == msg.sender, "The caller must be the sender."); require(transaction.status == Status.NoDispute, "The transaction shouldn't be disputed."); require(_amount <= transaction.amount, "The amount paid has to be less than or equal to the transaction."); transaction.receiver.transfer(_amount); transaction.amount -= _amount; emit Payment(_transactionID, _amount, msg.sender); } /** @dev Reimburse sender. To be called if the good or service can't be fully provided. * @param _transactionID The index of the transaction. * @param _amountReimbursed Amount to reimburse in wei. */ function reimburse(uint _transactionID, uint _amountReimbursed) public { Transaction storage transaction = transactions[_transactionID]; require(transaction.receiver == msg.sender, "The caller must be the receiver."); require(transaction.status == Status.NoDispute, "The transaction shouldn't be disputed."); require(_amountReimbursed <= transaction.amount, "The amount reimbursed has to be less or equal than the transaction."); transaction.sender.transfer(_amountReimbursed); transaction.amount -= _amountReimbursed; emit Payment(_transactionID, _amountReimbursed, msg.sender); } /** @dev Transfer the transaction's amount to the receiver if the timeout has passed. * @param _transactionID The index of the transaction. */ function executeTransaction(uint _transactionID) public { Transaction storage transaction = transactions[_transactionID]; require(now - transaction.lastInteraction >= transaction.timeoutPayment, "The timeout has not passed yet."); require(transaction.status == Status.NoDispute, "The transaction shouldn't be disputed."); transaction.receiver.transfer(transaction.amount); transaction.amount = 0; transaction.status = Status.Resolved; } /** @dev Reimburse sender if receiver fails to pay the fee. * @param _transactionID The index of the transaction. */ function timeOutBySender(uint _transactionID) public { Transaction storage transaction = transactions[_transactionID]; require(transaction.status == Status.WaitingReceiver, "The transaction is not waiting on the receiver."); require(now - transaction.lastInteraction >= feeTimeout, "Timeout time has not passed yet."); if (transaction.receiverFee != 0) { transaction.receiver.send(transaction.receiverFee); transaction.receiverFee = 0; } executeRuling(_transactionID, uint(Party.Sender)); } /** @dev Pay receiver if sender fails to pay the fee. * @param _transactionID The index of the transaction. */ function timeOutByReceiver(uint _transactionID) public { Transaction storage transaction = transactions[_transactionID]; require(transaction.status == Status.WaitingSender, "The transaction is not waiting on the sender."); require(now - transaction.lastInteraction >= feeTimeout, "Timeout time has not passed yet."); if (transaction.senderFee != 0) { transaction.sender.send(transaction.senderFee); transaction.senderFee = 0; } executeRuling(_transactionID, uint(Party.Receiver)); } /** @dev Pay the arbitration fee to raise a dispute. To be called by the sender. UNTRUSTED. * Note that the arbitrator can have createDispute throw, which will make this function throw and therefore lead to a party being timed-out. * This is not a vulnerability as the arbitrator can rule in favor of one party anyway. * @param _transactionID The index of the transaction. */ function payArbitrationFeeBySender(uint _transactionID) public payable { Transaction storage transaction = transactions[_transactionID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require(transaction.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed."); require(msg.sender == transaction.sender, "The caller must be the sender."); transaction.senderFee += msg.value; // Require that the total pay at least the arbitration cost. require(transaction.senderFee >= arbitrationCost, "The sender fee must cover arbitration costs."); transaction.lastInteraction = now; // The receiver still has to pay. This can also happen if he has paid, but arbitrationCost has increased. if (transaction.receiverFee < arbitrationCost) { transaction.status = Status.WaitingReceiver; emit HasToPayFee(_transactionID, Party.Receiver); } else { // The receiver has also paid the fee. We create the dispute. raiseDispute(_transactionID, arbitrationCost); } } /** @dev Pay the arbitration fee to raise a dispute. To be called by the receiver. UNTRUSTED. * Note that this function mirrors payArbitrationFeeBySender. * @param _transactionID The index of the transaction. */ function payArbitrationFeeByReceiver(uint _transactionID) public payable { Transaction storage transaction = transactions[_transactionID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require(transaction.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed."); require(msg.sender == transaction.receiver, "The caller must be the receiver."); transaction.receiverFee += msg.value; // Require that the total paid to be at least the arbitration cost. require(transaction.receiverFee >= arbitrationCost, "The receiver fee must cover arbitration costs."); transaction.lastInteraction = now; // The sender still has to pay. This can also happen if he has paid, but arbitrationCost has increased. if (transaction.senderFee < arbitrationCost) { transaction.status = Status.WaitingSender; emit HasToPayFee(_transactionID, Party.Sender); } else { // The sender has also paid the fee. We create the dispute. raiseDispute(_transactionID, arbitrationCost); } } /** @dev Create a dispute. UNTRUSTED. * @param _transactionID The index of the transaction. * @param _arbitrationCost Amount to pay the arbitrator. */ function raiseDispute(uint _transactionID, uint _arbitrationCost) internal { Transaction storage transaction = transactions[_transactionID]; transaction.status = Status.DisputeCreated; transaction.disputeId = arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES, arbitratorExtraData); disputeIDtoTransactionID[transaction.disputeId] = _transactionID; transaction.rounds.length++; emit Dispute(arbitrator, transaction.disputeId, _transactionID, _transactionID); // Refund sender if it overpaid. if (transaction.senderFee > _arbitrationCost) { uint extraFeeSender = transaction.senderFee - _arbitrationCost; transaction.senderFee = _arbitrationCost; transaction.sender.send(extraFeeSender); } // Refund receiver if it overpaid. if (transaction.receiverFee > _arbitrationCost) { uint extraFeeReceiver = transaction.receiverFee - _arbitrationCost; transaction.receiverFee = _arbitrationCost; transaction.receiver.send(extraFeeReceiver); } } /** @dev Submit a reference to evidence. EVENT. * @param _transactionID The index of the transaction. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _transactionID, string _evidence) public { Transaction storage transaction = transactions[_transactionID]; require( msg.sender == transaction.sender || msg.sender == transaction.receiver, "The caller must be the sender or the receiver." ); require( transaction.status < Status.Resolved, "Must not send evidence if the dispute is resolved." ); emit Evidence(arbitrator, _transactionID, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. * @param _transactionID The ID of the disputed transaction. * @param _side The party that pays the appeal fee. */ function fundAppeal(uint _transactionID, Party _side) public payable { Transaction storage transaction = transactions[_transactionID]; require(_side == Party.Sender || _side == Party.Receiver, "Wrong party."); require(transaction.status == Status.DisputeCreated, "No dispute to appeal"); require(arbitrator.disputeStatus(transaction.disputeId) == Arbitrator.DisputeStatus.Appealable, "Dispute is not appealable."); (uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(transaction.disputeId); require(now >= appealPeriodStart && now < appealPeriodEnd, "Funding must be made within the appeal period."); uint winner = arbitrator.currentRuling(transaction.disputeId); uint multiplier; if (winner == uint(_side)){ multiplier = winnerStakeMultiplier; } else if (winner == 0){ multiplier = sharedStakeMultiplier; } else { require(now - appealPeriodStart < (appealPeriodEnd - appealPeriodStart)/2, "The loser must pay during the first half of the appeal period."); multiplier = loserStakeMultiplier; } Round storage round = transaction.rounds[transaction.rounds.length - 1]; require(!round.hasPaid[uint(_side)], "Appeal fee has already been paid."); uint appealCost = arbitrator.appealCost(transaction.disputeId, arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(msg.value, totalCost.subCap(round.paidFees[uint(_side)])); round.contributions[msg.sender][uint(_side)] += contribution; round.paidFees[uint(_side)] += contribution; round.feeRewards += contribution; if (round.paidFees[uint(_side)] >= totalCost) { round.hasPaid[uint(_side)] = true; emit HasPaidAppealFee(_transactionID, _side); } // Reimburse leftover ETH. msg.sender.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. // Create an appeal if each side is funded. if (round.hasPaid[uint(Party.Sender)] && round.hasPaid[uint(Party.Receiver)]) { arbitrator.appeal.value(appealCost)(transaction.disputeId, arbitratorExtraData); transaction.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Witdraws contributions of appeal rounds. Reimburses contributions if the appeal was not fully funded. If the appeal was fully funded, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions. * @param _transactionID The ID of the associated transaction. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards(address _beneficiary, uint _transactionID, uint _round) public { Transaction storage transaction = transactions[_transactionID]; Round storage round = transaction.rounds[_round]; require(transaction.status == Status.Resolved, "The transaction should be resolved."); uint reward; if (!round.hasPaid[uint(Party.Sender)] || !round.hasPaid[uint(Party.Receiver)]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_beneficiary][uint(Party.Sender)] + round.contributions[_beneficiary][uint(Party.Receiver)]; } else if (transaction.ruling == uint(Party.None)) { // Reimburse unspent fees proportionally if there is no winner and loser. uint rewardSender = round.paidFees[uint(Party.Sender)] > 0 ? (round.contributions[_beneficiary][uint(Party.Sender)] * round.feeRewards) / (round.paidFees[uint(Party.Sender)] + round.paidFees[uint(Party.Receiver)]) : 0; uint rewardReceiver = round.paidFees[uint(Party.Receiver)] > 0 ? (round.contributions[_beneficiary][uint(Party.Receiver)] * round.feeRewards) / (round.paidFees[uint(Party.Sender)] + round.paidFees[uint(Party.Receiver)]) : 0; reward = rewardSender + rewardReceiver; } else { // Reward the winner. reward = round.paidFees[transaction.ruling] > 0 ? (round.contributions[_beneficiary][transaction.ruling] * round.feeRewards) / round.paidFees[transaction.ruling] : 0; } round.contributions[_beneficiary][uint(Party.Sender)] = 0; round.contributions[_beneficiary][uint(Party.Receiver)] = 0; _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Withdraws contributions of multiple appeal rounds at once. This function is O(n) where n is the number of rounds. This could exceed the gas limit, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions. * @param _transactionID The ID of the associated transaction. * @param _cursor The round from where to start withdrawing. * @param _count The number of rounds to iterate. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw(address _beneficiary, uint _transactionID, uint _cursor, uint _count) public { Transaction storage transaction = transactions[_transactionID]; for (uint i = _cursor; i<transaction.rounds.length && (_count==0 || i<_cursor+_count); i++) withdrawFeesAndRewards(_beneficiary, _transactionID, i); } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { Party resultRuling = Party(_ruling); uint transactionID = disputeIDtoTransactionID[_disputeID]; Transaction storage transaction = transactions[transactionID]; Round storage round = transaction.rounds[transaction.rounds.length - 1]; require(msg.sender == address(arbitrator), "The caller must be the arbitrator."); require(transaction.status == Status.DisputeCreated, "The dispute has already been resolved."); // If only one side paid its fees we assume the ruling to be in its favor. if (round.hasPaid[uint(Party.Sender)] == true) resultRuling = Party.Sender; else if (round.hasPaid[uint(Party.Receiver)] == true) resultRuling = Party.Receiver; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(transactionID, uint(resultRuling)); } /** @dev Execute a ruling of a dispute. It reimburses the fee to the winning party. * @param _transactionID The index of the transaction. * @param _ruling Ruling given by the arbitrator. */ function executeRuling(uint _transactionID, uint _ruling) internal { Transaction storage transaction = transactions[_transactionID]; require(_ruling <= AMOUNT_OF_CHOICES, "Invalid ruling."); // Give the arbitration fee back. // Note that we use send to prevent a party from blocking the execution. if (_ruling == uint(Party.Sender)) { transaction.sender.send(transaction.senderFee + transaction.amount); } else if (_ruling == uint(Party.Receiver)) { transaction.receiver.send(transaction.receiverFee + transaction.amount); } else { uint split_amount = (transaction.senderFee + transaction.amount) / 2; transaction.sender.send(split_amount); transaction.receiver.send(split_amount); } transaction.amount = 0; transaction.senderFee = 0; transaction.receiverFee = 0; transaction.status = Status.Resolved; transaction.ruling = _ruling; } // **************************** // // * Constant getters * // // **************************** // /** @dev Returns the sum of withdrawable wei from appeal rounds. This function is O(n), where n is the number of rounds of the transaction. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _transactionID The index of the transaction. * @param _beneficiary The contributor for which to query. * @return The total amount of wei available to withdraw. */ function amountWithdrawable(uint _transactionID, address _beneficiary) public view returns (uint total){ Transaction storage transaction = transactions[_transactionID]; if (transaction.status != Status.Resolved) return total; for (uint i = 0; i < transaction.rounds.length; i++) { Round storage round = transaction.rounds[i]; if (!round.hasPaid[uint(Party.Sender)] || !round.hasPaid[uint(Party.Receiver)]) { total += round.contributions[_beneficiary][uint(Party.Sender)] + round.contributions[_beneficiary][uint(Party.Receiver)]; } else if (transaction.ruling == uint(Party.None)) { uint rewardSender = round.paidFees[uint(Party.Sender)] > 0 ? (round.contributions[_beneficiary][uint(Party.Sender)] * round.feeRewards) / (round.paidFees[uint(Party.Sender)] + round.paidFees[uint(Party.Receiver)]) : 0; uint rewardReceiver = round.paidFees[uint(Party.Receiver)] > 0 ? (round.contributions[_beneficiary][uint(Party.Receiver)] * round.feeRewards) / (round.paidFees[uint(Party.Sender)] + round.paidFees[uint(Party.Receiver)]) : 0; total += rewardSender + rewardReceiver; } else { total += round.paidFees[uint(transaction.ruling)] > 0 ? (round.contributions[_beneficiary][uint(transaction.ruling)] * round.feeRewards) / round.paidFees[uint(transaction.ruling)] : 0; } } return total; } /** @dev Getter to know the count of transactions. * @return countTransactions The count of transactions. */ function getCountTransactions() public view returns (uint countTransactions) { return transactions.length; } /** @dev Gets the number of rounds of the specific transaction. * @param _transactionID The ID of the transaction. * @return The number of rounds. */ function getNumberOfRounds(uint _transactionID) public view returns (uint) { Transaction storage transaction = transactions[_transactionID]; return transaction.rounds.length; } /** @dev Gets the contributions made by a party for a given round of the appeal. * @param _transactionID The ID of the transaction. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return The contributions. */ function getContributions( uint _transactionID, uint _round, address _contributor ) public view returns(uint[3] contributions) { Transaction storage transaction = transactions[_transactionID]; Round storage round = transaction.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Gets the information on a round of a transaction. * @param _transactionID The ID of the transaction. * @param _round The round to query. * @return The round information. */ function getRoundInfo(uint _transactionID, uint _round) public view returns ( uint[3] paidFees, bool[3] hasPaid, uint feeRewards ) { Transaction storage transaction = transactions[_transactionID]; Round storage round = transaction.rounds[_round]; return ( round.paidFees, round.hasPaid, round.feeRewards ); } /** @dev Get IDs for transactions where the specified address is the receiver and/or the sender. * This function must be used by the UI and not by other smart contracts. * Note that the complexity is O(t), where t is amount of arbitrable transactions. * @param _address The specified address. * @return transactionIDs The transaction IDs. */ function getTransactionIDsByAddress(address _address) public view returns (uint[] transactionIDs) { uint count = 0; for (uint i = 0; i < transactions.length; i++) { if (transactions[i].sender == _address || transactions[i].receiver == _address) count++; } transactionIDs = new uint[](count); count = 0; for (uint j = 0; j < transactions.length; j++) { if (transactions[j].sender == _address || transactions[j].receiver == _address) transactionIDs[count++] = j; } } }
Create a dispute. UNTRUSTED. _transactionID The index of the transaction. _arbitrationCost Amount to pay the arbitrator./ Refund sender if it overpaid. Refund receiver if it overpaid.
function raiseDispute(uint _transactionID, uint _arbitrationCost) internal { Transaction storage transaction = transactions[_transactionID]; transaction.status = Status.DisputeCreated; transaction.disputeId = arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES, arbitratorExtraData); disputeIDtoTransactionID[transaction.disputeId] = _transactionID; transaction.rounds.length++; emit Dispute(arbitrator, transaction.disputeId, _transactionID, _transactionID); if (transaction.senderFee > _arbitrationCost) { uint extraFeeSender = transaction.senderFee - _arbitrationCost; transaction.senderFee = _arbitrationCost; transaction.sender.send(extraFeeSender); } if (transaction.receiverFee > _arbitrationCost) { uint extraFeeReceiver = transaction.receiverFee - _arbitrationCost; transaction.receiverFee = _arbitrationCost; transaction.receiver.send(extraFeeReceiver); } }
12,734,867
./full_match/1/0x75Cd3F538c091C1D514aB1aD9832f54198CAceC0/sources/src/GnarsHD.sol
Returns the tokenId of the Gnar HD by index Delegates to the Gnars V2 contract
function tokenByIndex(uint256 _index) external view returns (uint256) { return gnarsV2.tokenByIndex(_index); }
16,430,904
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "../../../interfaces/IEscrowTicketer.sol"; import "../../../interfaces/ISeenHausNFT.sol"; import "../../../util/StringUtils.sol"; import "../MarketClientBase.sol"; import "./ItemsTicketerStorage.sol"; /** * @title ItemsTicketer * * @notice An IEscrowTicketer contract implemented with ERC-1155. * * Holders of this style of ticket have the right to transfer or * claim a given number of a physical consignment, escrowed by * Seen.Haus. * * Since this is an ERC155 implementation, the holder can * sell / transfer part or all of the balance of their ticketed * items rather than claim them all. * * N.B.: This contract supports piece-level reseller behavior, * e.g., an entity scooping up a bunch of the available items * in a multi-edition sale with the purpose of flipping each * item individually to make maximum profit. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract ItemsTicketer is ItemsTicketerStorage, StringUtils, IEscrowTicketer, MarketClientBase, ERC1155Upgradeable { /** * @notice Initializer */ function initialize() public { __ERC1155_init(ESCROW_TICKET_URI); } /** * @notice The getNextTicket getter * @dev does not increment counter */ function getNextTicket() external view override returns (uint256) { return nextTicket; } /** * @notice Get info about the ticket */ function getTicket(uint256 _ticketId) external view override returns (EscrowTicket memory) { require(_ticketId < nextTicket, "Ticket does not exist"); return tickets[_ticketId]; } /** * @notice Get how many claims can be made using tickets (does not change after ticket burns) */ function getTicketClaimableCount(uint256 _consignmentId) external view override returns (uint256) { return consignmentIdToTicketClaimableCount[_consignmentId]; } /** * @notice Gets the URI for the ticket metadata * * IEscrowTicketer method that normalizes how you get the URI, * since ERC721 and ERC1155 differ in approach. * * @param _ticketId - the token id of the ticket */ function getTicketURI(uint256 _ticketId) external pure override returns (string memory) { return uri(_ticketId); } /** * @notice Get the token URI * * ex: tokenId = 12 * https://seen.haus/ticket/metadata/items-ticketer/12 * * @param _tokenId - the ticket's token id * @return tokenURI - the URI for the given token id's metadata */ function uri(uint256 _tokenId) public pure override returns (string memory) { string memory base = strConcat(ESCROW_TICKET_URI, "items-ticketer/"); return strConcat(base, uintToStr(_tokenId)); } /** * Issue an escrow ticket to the buyer * * For physical consignments, Seen.Haus must hold the items in escrow * until the buyer(s) claim them. * * When a buyer wins an auction or makes a purchase in a sale, the market * handler contract they interacted with will call this method to issue an * escrow ticket, which is an NFT that can be sold, transferred, or claimed. * * Reverts if token amount hasn't already been transferred to this contract * * @param _consignmentId - the id of the consignment being sold * @param _amount - the amount of the given token to escrow * @param _buyer - the buyer of the escrowed item(s) to whom the ticket is issued */ function issueTicket(uint256 _consignmentId, uint256 _amount, address payable _buyer) external override onlyRole(MARKET_HANDLER) { // Get the MarketController IMarketController marketController = getMarketController(); // Fetch consignment (reverting if consignment doesn't exist) Consignment memory consignment = marketController.getConsignment(_consignmentId); // Make sure amount is non-zero require(_amount > 0, "Token amount cannot be zero."); consignmentIdToTicketClaimableCount[_consignmentId] += _amount; // Make sure that there can't be more tickets issued than the maximum possible consignment allocation require(consignmentIdToTicketClaimableCount[_consignmentId] <= consignment.supply, "Can't issue more tickets than max possible allowed for consignment"); // Get the ticketed token Token memory token = ISeenHausNFT(consignment.tokenAddress).getTokenInfo(consignment.tokenId); // Create and store escrow ticket uint256 ticketId = nextTicket++; EscrowTicket storage ticket = tickets[ticketId]; ticket.amount = _amount; ticket.consignmentId = _consignmentId; ticket.id = ticketId; ticket.itemURI = token.uri; // Mint escrow ticket and send to buyer _mint(_buyer, ticketId, _amount, new bytes(0x0)); // Notify listeners about state change emit TicketIssued(ticketId, _consignmentId, _buyer, _amount); } /** * Claim escrowed items associated with the ticket. * * @param _ticketId - the ticket representing the escrowed item(s) */ function claim(uint256 _ticketId) external override { // Get the MarketController IMarketController marketController = getMarketController(); // Make sure the ticket exists EscrowTicket memory ticket = tickets[_ticketId]; require(ticket.id == _ticketId, "Ticket does not exist"); uint256 amount = balanceOf(msg.sender, _ticketId); require(amount > 0, "Caller has no balance for this ticket"); // Burn the caller's balance _burn(msg.sender, _ticketId, amount); // Reduce the ticket's amount by the claim amount ticket.amount -= amount; // When entire supply is claimed and burned, delete the ticket structure if (ticket.amount == 0) { delete tickets[_ticketId]; } else { tickets[_ticketId] = ticket; } // Release the consignment to claimant marketController.releaseConsignment(ticket.consignmentId, amount, msg.sender); // Notify listeners of state change emit TicketClaimed(_ticketId, msg.sender, amount); } /** * @notice Implementation of the {IERC165} interface. * * N.B. This method is inherited from several parents and * the compiler cannot decide which to use. Thus, they must * be overridden here. * * if you just call super.supportsInterface, it chooses * 'the most derived contract'. But that's not good for this * particular function because you may inherit from several * IERC165 contracts, and all concrete ones need to be allowed * to respond. */ function supportsInterface(bytes4 interfaceId) public view override(ERC1155Upgradeable) returns (bool) { return ( interfaceId == type(IEscrowTicketer).interfaceId || super.supportsInterface(interfaceId) ); } } // 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.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.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: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IEscrowTicketer * * @notice Manages the issue and claim of escrow tickets. * * The ERC-165 identifier for this interface is: 0x73811679 * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IEscrowTicketer { event TicketIssued(uint256 ticketId, uint256 indexed consignmentId, address indexed buyer, uint256 amount); event TicketClaimed(uint256 ticketId, address indexed claimant, uint256 amount); /** * @notice The nextTicket getter */ function getNextTicket() external view returns (uint256); /** * @notice Get info about the ticket */ function getTicket(uint256 _ticketId) external view returns (SeenTypes.EscrowTicket memory); /** * @notice Get how many claims can be made using tickets (does not change after ticket burns) */ function getTicketClaimableCount(uint256 _consignmentId) external view returns (uint256); /** * @notice Gets the URI for the ticket metadata * * This method normalizes how you get the URI, * since ERC721 and ERC1155 differ in approach * * @param _ticketId - the token id of the ticket */ function getTicketURI(uint256 _ticketId) external view returns (string memory); /** * Issue an escrow ticket to the buyer * * For physical consignments, Seen.Haus must hold the items in escrow * until the buyer(s) claim them. * * When a buyer wins an auction or makes a purchase in a sale, the market * handler contract they interacted with will call this method to issue an * escrow ticket, which is an NFT that can be sold, transferred, or claimed. * * @param _consignmentId - the id of the consignment being sold * @param _amount - the amount of the given token to escrow * @param _buyer - the buyer of the escrowed item(s) to whom the ticket is issued */ function issueTicket(uint256 _consignmentId, uint256 _amount, address payable _buyer) external; /** * Claim the holder's escrowed items associated with the ticket. * * @param _ticketId - the ticket representing the escrowed items */ function claim(uint256 _ticketId) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "../domain/SeenTypes.sol"; import "./IERC2981.sol"; /** * @title ISeenHausNFT * * @notice This is the interface for the Seen.Haus ERC-1155 NFT contract. * * The ERC-165 identifier for this interface is: 0x34d6028b * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface ISeenHausNFT is IERC2981, IERC1155Upgradeable { /** * @notice The nextToken getter * @dev does not increment counter */ function getNextToken() external view returns (uint256 nextToken); /** * @notice Get the info about a given token. * * @param _tokenId - the id of the token to check * @return tokenInfo - the info about the token. See: {SeenTypes.Token} */ function getTokenInfo(uint256 _tokenId) external view returns (SeenTypes.Token memory tokenInfo); /** * @notice Check if a given token id corresponds to a physical lot. * * @param _tokenId - the id of the token to check * @return physical - true if the item corresponds to a physical lot */ function isPhysical(uint256 _tokenId) external returns (bool); /** * @notice Mint a given supply of a token, marking it as physical. * * Entire supply must be minted at once. * More cannot be minted later for the same token id. * Can only be called by an address with the ESCROW_AGENT role. * Token supply is sent to the caller. * * @param _supply - the supply of the token * @param _creator - the creator of the NFT (where the royalties will go) * @param _tokenURI - the URI of the token metadata * * @return consignment - the registered primary market consignment of the newly minted token */ function mintPhysical( uint256 _supply, address payable _creator, string memory _tokenURI, uint16 _royaltyPercentage ) external returns(SeenTypes.Consignment memory consignment); /** * @notice Mint a given supply of a token. * * Entire supply must be minted at once. * More cannot be minted later for the same token id. * Can only be called by an address with the MINTER role. * Token supply is sent to the caller's address. * * @param _supply - the supply of the token * @param _creator - the creator of the NFT (where the royalties will go) * @param _tokenURI - the URI of the token metadata * * @return consignment - the registered primary market consignment of the newly minted token */ function mintDigital( uint256 _supply, address payable _creator, string memory _tokenURI, uint16 _royaltyPercentage ) external returns(SeenTypes.Consignment memory consignment); /** * @dev Returns the address of the current owner. */ function owner() external view returns (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() external; /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title String Utils * * Functions for converting numbers to strings and concatenating strings. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract StringUtils { /** * @notice Convert a `uint` value to a `string` * via OraclizeAPI - MIT licence * https://github.com/provable-things/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol#L896 * @param _i the `uint` value to be converted * @return result the `string` representation of the given `uint` value */ function uintToStr(uint _i) public pure returns (string memory result) { unchecked { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + _i % 10)); _i /= 10; } result = string(bstr); } } /** * @notice Concatenate two strings * @param _a the first string * @param _b the second string * @return result the concatenation of `_a` and `_b` */ function strConcat(string memory _a, string memory _b) public pure returns(string memory result) { result = string(abi.encodePacked(bytes(_a), bytes(_b))); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../interfaces/IMarketController.sol"; import "../../domain/SeenConstants.sol"; import "../../domain/SeenTypes.sol"; import "./MarketClientLib.sol"; /** * @title MarketClientBase * * @notice Extended by Seen.Haus contracts that need to communicate with the * MarketController, but are NOT facets of the MarketDiamond. * * Market client contracts include SeenHausNFT, ItemsTicketer, and LotsTicketer * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ abstract contract MarketClientBase is SeenTypes, SeenConstants { /** * @dev Modifier that checks that the caller has a specific role. * * Reverts if caller doesn't have role. * * See: {AccessController.hasRole} */ modifier onlyRole(bytes32 role) { require(MarketClientLib.hasRole(role), "Caller doesn't have role"); _; } /** * @notice Get the MarketController from the MarketClientProxy's storage * * @return IMarketController address */ function getMarketController() internal pure returns (IMarketController) { MarketClientLib.ProxyStorage memory ps = MarketClientLib.proxyStorage(); return ps.marketController; } /** * @notice Get a percentage of a given amount. * * N.B. Represent ercentage values are stored * as unsigned integers, the result of multiplying the given percentage by 100: * e.g, 1.75% = 175, 100% = 10000 * * @param _amount - the amount to return a percentage of * @param _percentage - the percentage value represented as above */ function getPercentageOf(uint256 _amount, uint16 _percentage) internal pure returns (uint256 share) { share = _amount * _percentage / 10000; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../../domain/SeenTypes.sol"; /** * @title ItemsTicketerStorage * @notice Splits storage away from the logic in ItemsTicketer.sol for maintainability * */ contract ItemsTicketerStorage is SeenTypes { // Ticket ID => Ticket mapping (uint256 => EscrowTicket) internal tickets; // Consignment ID => Ticket Claimable Count (does not change after ticket burns) mapping (uint256 => uint256) internal consignmentIdToTicketClaimableCount; /// @dev Next ticket number uint256 internal nextTicket; } // 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 "../../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 "../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; /** * @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 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; 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 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; /** * @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: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title SeenTypes * * @notice Enums and structs used by the Seen.Haus contract ecosystem. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SeenTypes { enum Market { Primary, Secondary } enum MarketHandler { Unhandled, Auction, Sale } enum Clock { Live, Trigger } enum Audience { Open, Staker, VipStaker } enum Outcome { Pending, Closed, Canceled } enum State { Pending, Running, Ended } enum Ticketer { Default, Lots, Items } struct Token { address payable creator; uint16 royaltyPercentage; bool isPhysical; uint256 id; uint256 supply; string uri; } struct Consignment { Market market; MarketHandler marketHandler; address payable seller; address tokenAddress; uint256 tokenId; uint256 supply; uint256 id; bool multiToken; bool released; uint256 releasedSupply; uint16 customFeePercentageBasisPoints; uint256 pendingPayout; } struct Auction { address payable buyer; uint256 consignmentId; uint256 start; uint256 duration; uint256 reserve; uint256 bid; Clock clock; State state; Outcome outcome; } struct Sale { uint256 consignmentId; uint256 start; uint256 price; uint256 perTxCap; State state; Outcome outcome; } struct EscrowTicket { uint256 amount; uint256 consignmentId; uint256 id; string itemURI; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @title IERC2981 interface * * @notice NFT Royalty Standard. * * See https://eips.ethereum.org/EIPS/eip-2981 */ interface IERC2981 is IERC165Upgradeable { /** * @notice Determine how much royalty is owed (if any) and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns ( address receiver, uint256 royaltyAmount ); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IMarketConfig.sol"; import "./IMarketConfigAdditional.sol"; import "./IMarketClerk.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * * The ERC-165 identifier for this interface is: 0xbb8dba77 * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketController is IMarketClerk, IMarketConfig, IMarketConfigAdditional {} // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title SeenConstants * * @notice Constants used by the Seen.Haus contract ecosystem. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SeenConstants { // Endpoint will serve dynamic metadata composed of ticket and ticketed item's info string internal constant ESCROW_TICKET_URI = "https://api.seen.haus/ticket/metadata/"; // Access Control Roles bytes32 internal constant ADMIN = keccak256("ADMIN"); // Deployer and any other admins as needed bytes32 internal constant SELLER = keccak256("SELLER"); // Approved sellers amd Seen.Haus reps bytes32 internal constant MINTER = keccak256("MINTER"); // Approved artists and Seen.Haus reps bytes32 internal constant ESCROW_AGENT = keccak256("ESCROW_AGENT"); // Seen.Haus Physical Item Escrow Agent bytes32 internal constant MARKET_HANDLER = keccak256("MARKET_HANDLER"); // Market Handler contracts bytes32 internal constant UPGRADER = keccak256("UPGRADER"); // Performs contract upgrades bytes32 internal constant MULTISIG = keccak256("MULTISIG"); // Admin role of MARKET_HANDLER & UPGRADER } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import "../../interfaces/IMarketController.sol"; /** * @title MarketClientLib * * Maintains the implementation address and the access and market controller addresses. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ library MarketClientLib { struct ProxyStorage { // The Seen.Haus AccessController address IAccessControlUpgradeable accessController; // The Seen.Haus MarketController address IMarketController marketController; // The implementation address address implementation; } /** * @dev Storage slot with the address of the Seen.Haus AccessController * This is obviously not a standard EIP-1967 slot. */ bytes32 internal constant PROXY_SLOT = keccak256('Seen.Haus.MarketClientProxy'); /** * @notice Get the Proxy storage slot * * @return ps - Proxy storage slot cast to ProxyStorage */ function proxyStorage() internal pure returns (ProxyStorage storage ps) { bytes32 position = PROXY_SLOT; assembly { ps.slot := position } } /** * @dev Checks that the caller has a specific role. * * Reverts if caller doesn't have role. * * See: {AccessController.hasRole} */ function hasRole(bytes32 role) internal view returns (bool) { ProxyStorage storage ps = proxyStorage(); return ps.accessController.hasRole(role, msg.sender); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * @dev Contributes its events and functions to the IMarketController interface * * The ERC-165 identifier for this interface is: 0x57f9f26d * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketConfig { /// Events event NFTAddressChanged(address indexed nft); event EscrowTicketerAddressChanged(address indexed escrowTicketer, SeenTypes.Ticketer indexed ticketerType); event StakingAddressChanged(address indexed staking); event MultisigAddressChanged(address indexed multisig); event VipStakerAmountChanged(uint256 indexed vipStakerAmount); event PrimaryFeePercentageChanged(uint16 indexed feePercentage); event SecondaryFeePercentageChanged(uint16 indexed feePercentage); event MaxRoyaltyPercentageChanged(uint16 indexed maxRoyaltyPercentage); event OutBidPercentageChanged(uint16 indexed outBidPercentage); event DefaultTicketerTypeChanged(SeenTypes.Ticketer indexed ticketerType); /** * @notice Sets the address of the xSEEN ERC-20 staking contract. * * Emits a NFTAddressChanged event. * * @param _nft - the address of the nft contract */ function setNft(address _nft) external; /** * @notice The nft getter */ function getNft() external view returns (address); /** * @notice Sets the address of the Seen.Haus lots-based escrow ticketer contract. * * Emits a EscrowTicketerAddressChanged event. * * @param _lotsTicketer - the address of the items-based escrow ticketer contract */ function setLotsTicketer(address _lotsTicketer) external; /** * @notice The lots-based escrow ticketer getter */ function getLotsTicketer() external view returns (address); /** * @notice Sets the address of the Seen.Haus items-based escrow ticketer contract. * * Emits a EscrowTicketerAddressChanged event. * * @param _itemsTicketer - the address of the items-based escrow ticketer contract */ function setItemsTicketer(address _itemsTicketer) external; /** * @notice The items-based escrow ticketer getter */ function getItemsTicketer() external view returns (address); /** * @notice Sets the address of the xSEEN ERC-20 staking contract. * * Emits a StakingAddressChanged event. * * @param _staking - the address of the staking contract */ function setStaking(address payable _staking) external; /** * @notice The staking getter */ function getStaking() external view returns (address payable); /** * @notice Sets the address of the Seen.Haus multi-sig wallet. * * Emits a MultisigAddressChanged event. * * @param _multisig - the address of the multi-sig wallet */ function setMultisig(address payable _multisig) external; /** * @notice The multisig getter */ function getMultisig() external view returns (address payable); /** * @notice Sets the VIP staker amount. * * Emits a VipStakerAmountChanged event. * * @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events */ function setVipStakerAmount(uint256 _vipStakerAmount) external; /** * @notice The vipStakerAmount getter */ function getVipStakerAmount() external view returns (uint256); /** * @notice Sets the marketplace fee percentage. * Emits a PrimaryFeePercentageChanged event. * * @param _primaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction * * N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setPrimaryFeePercentage(uint16 _primaryFeePercentage) external; /** * @notice Sets the marketplace fee percentage. * Emits a SecondaryFeePercentageChanged event. * * @param _secondaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties) * * N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setSecondaryFeePercentage(uint16 _secondaryFeePercentage) external; /** * @notice The primaryFeePercentage and secondaryFeePercentage getter */ function getFeePercentage(SeenTypes.Market _market) external view returns (uint16); /** * @notice Sets the external marketplace maximum royalty percentage. * * Emits a MaxRoyaltyPercentageChanged event. * * @param _maxRoyaltyPercentage - the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty */ function setMaxRoyaltyPercentage(uint16 _maxRoyaltyPercentage) external; /** * @notice The maxRoyaltyPercentage getter */ function getMaxRoyaltyPercentage() external view returns (uint16); /** * @notice Sets the marketplace auction outbid percentage. * * Emits a OutBidPercentageChanged event. * * @param _outBidPercentage - the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail */ function setOutBidPercentage(uint16 _outBidPercentage) external; /** * @notice The outBidPercentage getter */ function getOutBidPercentage() external view returns (uint16); /** * @notice Sets the default escrow ticketer type. * * Emits a DefaultTicketerTypeChanged event. * * Reverts if _ticketerType is Ticketer.Default * Reverts if _ticketerType is already the defaultTicketerType * * @param _ticketerType - the new default escrow ticketer type. */ function setDefaultTicketerType(SeenTypes.Ticketer _ticketerType) external; /** * @notice The defaultTicketerType getter */ function getDefaultTicketerType() external view returns (SeenTypes.Ticketer); /** * @notice Get the Escrow Ticketer to be used for a given consignment * * If a specific ticketer has not been set for the consignment, * the default escrow ticketer will be returned. * * @param _consignmentId - the id of the consignment * @return ticketer = the address of the escrow ticketer to use */ function getEscrowTicketer(uint256 _consignmentId) external view returns (address ticketer); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * @dev Contributes its events and functions to the IMarketController interface * * The ERC-165 identifier for this interface is: 0x57f9f26d * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketConfigAdditional { /// Events event AllowExternalTokensOnSecondaryChanged(bool indexed status); event EscrowAgentFeeChanged(address indexed escrowAgent, uint16 fee); /** * @notice Sets whether or not external tokens can be listed on secondary market * * Emits an AllowExternalTokensOnSecondaryChanged event. * * @param _status - boolean of whether or not external tokens are allowed */ function setAllowExternalTokensOnSecondary(bool _status) external; /** * @notice The allowExternalTokensOnSecondary getter */ function getAllowExternalTokensOnSecondary() external view returns (bool status); /** * @notice The escrow agent fee getter */ function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress) external view returns (uint16); /** * @notice The escrow agent fee setter */ function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "../domain/SeenTypes.sol"; /** * @title IMarketClerk * * @notice Manages consignments for the Seen.Haus contract suite. * * The ERC-165 identifier for this interface is: 0xec74481a * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketClerk is IERC1155ReceiverUpgradeable, IERC721ReceiverUpgradeable { /// Events event ConsignmentTicketerChanged(uint256 indexed consignmentId, SeenTypes.Ticketer indexed ticketerType); event ConsignmentFeeChanged(uint256 indexed consignmentId, uint16 customConsignmentFee); event ConsignmentPendingPayoutSet(uint256 indexed consignmentId, uint256 amount); event ConsignmentRegistered(address indexed consignor, address indexed seller, SeenTypes.Consignment consignment); event ConsignmentMarketed(address indexed consignor, address indexed seller, uint256 indexed consignmentId); event ConsignmentReleased(uint256 indexed consignmentId, uint256 amount, address releasedTo); /** * @notice The nextConsignment getter */ function getNextConsignment() external view returns (uint256); /** * @notice The consignment getter */ function getConsignment(uint256 _consignmentId) external view returns (SeenTypes.Consignment memory); /** * @notice Get the remaining supply of the given consignment. * * @param _consignmentId - the id of the consignment * @return uint256 - the remaining supply held by the MarketController */ function getUnreleasedSupply(uint256 _consignmentId) external view returns(uint256); /** * @notice Get the consignor of the given consignment * * @param _consignmentId - the id of the consignment * @return address - consigner's address */ function getConsignor(uint256 _consignmentId) external view returns(address); /** * @notice Registers a new consignment for sale or auction. * * Emits a ConsignmentRegistered event. * * @param _market - the market for the consignment. See {SeenTypes.Market} * @param _consignor - the address executing the consignment transaction * @param _seller - the seller of the consignment * @param _tokenAddress - the contract address issuing the NFT behind the consignment * @param _tokenId - the id of the token being consigned * @param _supply - the amount of the token being consigned * * @return Consignment - the registered consignment */ function registerConsignment( SeenTypes.Market _market, address _consignor, address payable _seller, address _tokenAddress, uint256 _tokenId, uint256 _supply ) external returns(SeenTypes.Consignment memory); /** * @notice Update consignment to indicate it has been marketed * * Emits a ConsignmentMarketed event. * * Reverts if consignment has already been marketed. * A consignment is considered as marketed if it has a marketHandler other than Unhandled. See: {SeenTypes.MarketHandler} * * @param _consignmentId - the id of the consignment */ function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external; /** * @notice Release the consigned item to a given address * * Emits a ConsignmentReleased event. * * Reverts if caller is does not have MARKET_HANDLER role. * * @param _consignmentId - the id of the consignment * @param _amount - the amount of the consigned supply to release * @param _releaseTo - the address to transfer the consigned token balance to */ function releaseConsignment(uint256 _consignmentId, uint256 _amount, address _releaseTo) external; /** * @notice Clears the pending payout value of a consignment * * Emits a ConsignmentPayoutSet event. * * Reverts if: * - caller is does not have MARKET_HANDLER role. * - consignment doesn't exist * * @param _consignmentId - the id of the consignment * @param _amount - the amount of that the consignment's pendingPayout must be set to */ function setConsignmentPendingPayout(uint256 _consignmentId, uint256 _amount) external; /** * @notice Set the type of Escrow Ticketer to be used for a consignment * * Default escrow ticketer is Ticketer.Lots. This only needs to be called * if overriding to Ticketer.Items for a given consignment. * * Emits a ConsignmentTicketerSet event. * Reverts if consignment is not registered. * * @param _consignmentId - the id of the consignment * @param _ticketerType - the type of ticketer to use. See: {SeenTypes.Ticketer} */ function setConsignmentTicketer(uint256 _consignmentId, SeenTypes.Ticketer _ticketerType) external; /** * @notice Set a custom fee percentage on a consignment (e.g. for "official" SEEN x Artist drops) * * Default escrow ticketer is Ticketer.Lots. This only needs to be called * if overriding to Ticketer.Items for a given consignment. * * Emits a ConsignmentFeeChanged event. * * Reverts if consignment doesn't exist * * * @param _consignmentId - the id of the consignment * @param _customFeePercentageBasisPoints - the custom fee percentage basis points to use * * N.B. _customFeePercentageBasisPoints percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setConsignmentCustomFee(uint256 _consignmentId, uint16 _customFeePercentageBasisPoints) external; } // 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 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; }
IEscrowTicketer Manages the issue and claim of escrow tickets. The ERC-165 identifier for this interface is: 0x73811679/
interface IEscrowTicketer { event TicketIssued(uint256 ticketId, uint256 indexed consignmentId, address indexed buyer, uint256 amount); event TicketClaimed(uint256 ticketId, address indexed claimant, uint256 amount); function getNextTicket() external view returns (uint256); function getTicket(uint256 _ticketId) external view returns (SeenTypes.EscrowTicket memory); function getTicketClaimableCount(uint256 _consignmentId) external view returns (uint256); function getTicketURI(uint256 _ticketId) external view returns (string memory); function issueTicket(uint256 _consignmentId, uint256 _amount, address payable _buyer) external; function claim(uint256 _ticketId) external; pragma solidity ^0.8.0; }
1,573,945
pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts 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 Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _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); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } /** * @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees. * @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its * children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf * node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a * checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow * accessing historic information. * * Example of a checkpointed binary sum tree: * * CURRENT PREVIOUS * * Level 2 100 ---------------------------------------- 70 * ______|_______ ______|_______ * / \ / \ * Level 1 34 66 ------------------------- 23 47 * _____|_____ _____|_____ _____|_____ _____|_____ * / \ / \ / \ / \ * Level 0 22 12 53 13 ----------- 22 1 17 30 * */ library HexSumTree { using SafeMath for uint256; using Checkpointing for Checkpointing.History; string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW"; string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST"; string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS"; string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES"; // Constants used to perform tree computations // To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN // The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64) uint256 private constant CHILDREN = 16; uint256 private constant BITS_IN_NIBBLE = 4; // All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree. uint256 private constant ITEMS_LEVEL = 0; // Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys // starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys // are computed based on their level and their children keys. uint256 private constant BASE_KEY = 0; // Timestamp used to checkpoint the first value of the tree height during initialization uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0); /** * @dev The tree is stored using the following structure: * - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value). * - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children. * - nextKey: The next key to be used to identify the next new value that will be inserted into the tree. */ struct Tree { uint256 nextKey; Checkpointing.History height; mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes; } /** * @dev Search params to traverse the tree caching previous results: * - time: Point in time to query the values being searched, this value shouldn't change during a search * - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves * - parentKey: Key of the parent of the nodes being analyzed at the given level for the search * - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list * - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total */ struct SearchParams { uint64 time; uint256 level; uint256 parentKey; uint256 foundValues; uint256 visitedTotal; } /** * @dev Initialize tree setting the next key and first height checkpoint */ function init(Tree storage self) internal { self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1); self.nextKey = BASE_KEY; } /** * @dev Insert a new item to the tree at given point in time * @param _time Point in time to register the given value * @param _value New numeric value to be added to the tree * @return Unique key identifying the new value inserted */ function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) { // As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be // always incrementing, starting from zero. Add a new level if necessary. uint256 key = self.nextKey++; _addLevelIfNecessary(self, key, _time); // If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of // the tree if necessary, and finally update sums cached in all the non-leaf nodes. if (_value > 0) { _add(self, ITEMS_LEVEL, key, _time, _value); _updateSums(self, key, _time, _value, true); } return key; } /** * @dev Set the value of a leaf node indexed by its key at given point in time * @param _time Point in time to set the given value * @param _key Key of the leaf node to be set in the tree * @param _value New numeric value to be set for the given key */ function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Set the new value for the requested leaf node uint256 lastValue = getItem(self, _key); _add(self, ITEMS_LEVEL, _key, _time, _value); // Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update. if (_value > lastValue) { _updateSums(self, _key, _time, _value - lastValue, true); } else if (_value < lastValue) { _updateSums(self, _key, _time, lastValue - _value, false); } } /** * @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta * @param _key Key of the leaf node to be updated in the tree * @param _time Point in time to update the given value * @param _delta Numeric delta to update the value of the given key * @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value */ function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Update the value of the requested leaf node based on the given delta uint256 lastValue = getItem(self, _key); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, ITEMS_LEVEL, _key, _time, newValue); // Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update. _updateSums(self, _key, _time, _delta, _positive); } /** * @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest * high value in case a value cannot be found. This function assumes the given list of given values to be * searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results. * @param _values Ordered list of values to be searched in the tree * @param _time Point in time to query the values being searched * @return keys List of keys found for each requested value in the same order * @return values List of node values found for each requested value in the same order */ function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view returns (uint256[] memory keys, uint256[] memory values) { require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES); // Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total uint256 total = getRecentTotalAt(self, _time); // No need for SafeMath: positive length of array already checked require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS); // Build search params for the first iteration uint256 rootLevel = getRecentHeightAt(self, _time); SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0); // These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies uint256 length = _values.length; keys = new uint256[](length); values = new uint256[](length); _search(self, _values, searchParams, keys, values); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree */ function getTotal(Tree storage self) internal view returns (uint256) { uint256 rootLevel = getHeight(self); return getNode(self, rootLevel, BASE_KEY); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a binary search for the root node, a linear one for the height. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getRecentNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the value of a certain leaf indexed by a given key * @param _key Key of the leaf node querying the value of */ function getItem(Tree storage self, uint256 _key) internal view returns (uint256) { return getNode(self, ITEMS_LEVEL, _key); } /** * @dev Tell the value of a certain leaf indexed by a given key at a given point in time * It uses a binary search. * @param _key Key of the leaf node querying the value of * @param _time Point in time to query the value of the requested leaf */ function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) { return getNodeAt(self, ITEMS_LEVEL, _key, _time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of */ function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) { return self.nodes[_level][_key].getLast(); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a binary search. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].get(_time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a linear search starting from the end. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].getRecent(_time); } /** * @dev Tell the height of the tree */ function getHeight(Tree storage self) internal view returns (uint256) { return self.height.getLast(); } /** * @dev Tell the height of the tree at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the height of the tree */ function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) { return self.height.getRecent(_time); } /** * @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated * @param _key Key of the leaf node to update the ancestors of * @param _time Point in time to update the ancestors' values of the given leaf node * @param _delta Numeric delta to update the ancestors' values of the given leaf node * @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values */ function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private { uint256 mask = uint256(-1); uint256 ancestorKey = _key; uint256 currentHeight = getHeight(self); for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) { // Build a mask to get the key of the ancestor at a certain level. For example: // Level 0: leaves don't have children // Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves) // Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves) // ... // Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height) mask = mask << BITS_IN_NIBBLE; // The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles // of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a // certain level applying the mask to the ancestor's key of the previous level. Note that for the first // iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated. ancestorKey = ancestorKey & mask; // Update value uint256 lastValue = getNode(self, level, ancestorKey); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, level, ancestorKey, _time, newValue); } // Check if there was an overflow. Note that we only need to check the value stored in the root since the // sum only increases going up through the tree. require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW); } /** * @dev Private function to add a new level to the tree based on a new key that will be inserted * @param _newKey New key willing to be inserted in the tree * @param _time Point in time when the new key will be inserted */ function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private { uint256 currentHeight = getHeight(self); if (_shouldAddLevel(currentHeight, _newKey)) { // Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we // are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of // this system having 2^256 items inserted is unrealistic. uint256 newHeight = currentHeight + 1; uint256 rootValue = getNode(self, currentHeight, BASE_KEY); _add(self, newHeight, BASE_KEY, _time, rootValue); self.height.add(_time, newHeight); } } /** * @dev Private function to register a new value in the history of a node at a given point in time * @param _level Level of the node to add a new value at a given point in time to * @param _key Key of the node to add a new value at a given point in time to * @param _time Point in time to register a value for the given node * @param _value Numeric value to be registered for the given node at a given point in time */ function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private { self.nodes[_level][_key].add(_time, _value); } /** * @dev Recursive pre-order traversal function * Every time it checks a node, it traverses the input array to find the initial subset of elements that are * below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always * the same, to avoid making extra copies, it just passes the number of values already found , to avoid * checking values that went through a different branch. The same happens with the result lists of keys and * values, these are the same on every recursion step. The visited total is carried over each iteration to * avoid having to subtract all elements in the array. * @param _values Ordered list of values to be searched in the tree * @param _params Search parameters for the current recursive step * @param _resultKeys List of keys found for each requested value in the same order * @param _resultValues List of node values found for each requested value in the same order */ function _search( Tree storage self, uint256[] memory _values, SearchParams memory _params, uint256[] memory _resultKeys, uint256[] memory _resultValues ) private view { uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE); for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) { // Return if we already found enough values if (_params.foundValues >= _values.length) { break; } // Build child node key shifting the child number to the position of the less significant nibble of // the keys for the level being analyzed, and adding it to the key of the parent node. For example, // for a tree with height 5, if we are checking the children of the second node of the level 3, whose // key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are: // Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000 // Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100 // Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200 // ... // Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00 uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble); uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time); // Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous // subset starting from the beginning, so we only need to know the length of that subset. uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue); uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal); // If there are some values included in the subtree of the child node, visit them if (subtreeIncludedValues > 0) { // If the child node being analyzed is a leaf, add it to the list of results a number of times equals // to the number of values that were included in it. Otherwise, descend one level. if (_params.level == ITEMS_LEVEL) { _copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues); } else { SearchParams memory nextLevelParams = SearchParams( _params.time, _params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero childNodeKey, _params.foundValues, _params.visitedTotal ); _search(self, _values, nextLevelParams, _resultKeys, _resultValues); } // Update the number of values that were already found _params.foundValues = _params.foundValues.add(subtreeIncludedValues); } // Update the visited total for the next node in this level _params.visitedTotal = newVisitedTotal; } } /** * @dev Private function to check if a new key can be added to the tree based on the current height of the tree * @param _currentHeight Current height of the tree to check if it supports adding the given key * @param _newKey Key willing to be added to the tree with the given current height * @return True if the current height of the tree should be increased to add the new key, false otherwise. */ function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) { // Build a mask that will match all the possible keys for the given height. For example: // Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys) // Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys) // ... // Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height) uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE); uint256 mask = uint256(-1) << shift; // Check if the given key can be represented in the tree with the current given height using the mask. return (_newKey & mask) != 0; } /** * @dev Private function to tell how many values of a list can be found in a subtree * @param _values List of values being searched in ascending order * @param _foundValues Number of values that were already found and should be ignore * @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it * @return Number of values in the list that are included in the given subtree */ function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) { // Look for all the values that can be found in the given subtree uint256 i = _foundValues; while (i < _values.length && _values[i] < _subtreeTotal) { i++; } return i - _foundValues; } /** * @dev Private function to copy a node a given number of times to a results list. This function assumes the given * results list have enough size to support the requested copy. * @param _from Index of the results list to start copying the given node * @param _times Number of times the given node will be copied * @param _key Key of the node to be copied * @param _resultKeys Lists of key results to copy the given node key to * @param _value Value of the node to be copied * @param _resultValues Lists of value results to copy the given node value to */ function _copyFoundNode( uint256 _from, uint256 _times, uint256 _key, uint256[] memory _resultKeys, uint256 _value, uint256[] memory _resultValues ) private pure { for (uint256 i = 0; i < _times; i++) { _resultKeys[_from + i] = _key; _resultValues[_from + i] = _value; } } } /** * @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree` */ library GuardiansTreeSortition { using SafeMath for uint256; using HexSumTree for HexSumTree.Tree; string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH"; string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH"; /** * @dev Search random items in the tree based on certain restrictions * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for * @param _termId Current term when the draft is being computed * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @param _sortitionIteration Number of sortitions already performed for the given draft * @return guardiansIds List of guardian ids obtained based on the requested search * @return guardiansBalances List of active balances for each guardian obtained based on the requested search */ function batchedRandomSearch( HexSumTree.Tree storage tree, bytes32 _termRandomness, uint256 _disputeId, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians, uint256 _sortitionIteration ) internal view returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances) { (uint256 low, uint256 high) = getSearchBatchBounds( tree, _termId, _selectedGuardians, _batchRequestedGuardians, _roundRequestedGuardians ); uint256[] memory balances = _computeSearchRandomBalances( _termRandomness, _disputeId, _sortitionIteration, _batchRequestedGuardians, low, high ); (guardiansIds, guardiansBalances) = tree.search(balances, _termId); require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH); require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH); } /** * @dev Get the bounds for a draft batch based on the active balances of the guardians * @param _termId Term ID of the active balances that will be used to compute the boundaries * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch * @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch */ function getSearchBatchBounds( HexSumTree.Tree storage tree, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians ) internal view returns (uint256 low, uint256 high) { uint256 totalActiveBalance = tree.getRecentTotalAt(_termId); low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians); high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); } /** * @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for (for randomness) * @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness) * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians * @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians * @return Random list of active balances to be searched in the guardians tree for the given draft batch */ function _computeSearchRandomBalances( bytes32 _termRandomness, uint256 _disputeId, uint256 _sortitionIteration, uint256 _batchRequestedGuardians, uint256 _lowBatchBound, uint256 _highBatchBound ) internal pure returns (uint256[] memory) { // Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the // random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10). require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH); uint256 interval = _highBatchBound - _lowBatchBound; // Compute an ordered list of random active balance to be searched in the guardians tree uint256[] memory balances = new uint256[](_batchRequestedGuardians); for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) { // Compute a random seed using: // - The inherent randomness associated to the term from blockhash // - The disputeId, so 2 disputes in the same term will have different outcomes // - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance // - The guardian number in this batch bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber)); // Compute a random active balance to be searched in the guardians tree using the generated seed within the // boundaries computed for the current batch. balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval); // Make sure it's ordered, flip values if necessary for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) { uint256 tmp = balances[i - 1]; balances[i - 1] = balances[i]; balances[i] = tmp; } } return balances; } } /* * SPDX-License-Identifier: MIT */ interface ILockManager { /** * @dev Tell whether a user can unlock a certain amount of tokens */ function canUnlock(address user, uint256 amount) external view returns (bool); } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable { using SafeERC20 for IERC20; using SafeMath for uint256; using PctHelpers for uint256; using HexSumTree for HexSumTree.Tree; using GuardiansTreeSortition for HexSumTree.Tree; string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT"; string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT"; string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT"; string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT"; string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN"; string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN"; string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN"; string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE"; string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED"; string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED"; string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT"; string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED"; string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK"; string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION"; string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION"; string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT"; string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED"; string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK"; // Address that will be used to burn guardian tokens address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD); // Maximum number of sortition iterations allowed per draft call uint256 internal constant MAX_DRAFT_ITERATIONS = 10; // "ERC20-lite" interface to provide help for tooling string public constant name = "Court Staked Aragon Network Token"; string public constant symbol = "sANT"; uint8 public constant decimals = 18; /** * @dev Guardians have three kind of balances, these are: * - active: tokens activated for the Court that can be locked in case the guardian is drafted * - locked: amount of active tokens that are locked for a draft * - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time * * Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others * are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians' * active balances cannot be affected during the current Court term, if guardians want to deactivate some of * their active tokens, their balance will be updated for the following term, and they won't be allowed to * withdraw them until the current term has ended. * * Note that even though guardians balances are stored separately, all the balances are held by this contract. */ struct Guardian { uint256 id; // Key in the guardians tree used for drafting uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts uint256 availableBalance; // Available tokens that can be withdrawn at any time uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked ActivationLocks activationLocks; // Guardian's activation locks DeactivationRequest deactivationRequest; // Guardian's pending deactivation request } /** * @dev Guardians can define lock managers to control their minimum active balance in the registry */ struct ActivationLocks { uint256 total; // Total amount of active balance locked mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager } /** * @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some * of their tokens, the tree will always be updated for the following term, and they won't be able to * withdraw the requested amount until the current term has finished. Thus, we need to keep track the term * when a token deactivation was requested and its corresponding amount. */ struct DeactivationRequest { uint256 amount; // Amount requested for deactivation uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens } /** * @dev Internal struct to wrap all the params required to perform guardians drafting */ struct DraftParams { bytes32 termRandomness; // Randomness seed to be used for the draft uint256 disputeId; // ID of the dispute being drafted uint64 termId; // Term ID of the dispute's draft term uint256 selectedGuardians; // Number of guardians already selected for the draft uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian uint256 iteration; // Sortition iteration number } // Maximum amount of total active balance that can be held in the registry uint256 public totalActiveBalanceLimit; // Guardian ERC20 token IERC20 public guardiansToken; // Mapping of guardian data indexed by address mapping (address => Guardian) internal guardiansByAddress; // Mapping of guardian addresses indexed by id mapping (uint256 => address) internal guardiansAddressById; // Tree to store guardians active balance by term for the drafting process HexSumTree.Tree internal tree; event Staked(address indexed guardian, uint256 amount, uint256 total); event Unstaked(address indexed guardian, uint256 amount, uint256 total); event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount); event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount); event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId); event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId); event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total); event GuardianBalanceLocked(address indexed guardian, uint256 amount); event GuardianBalanceUnlocked(address indexed guardian, uint256 amount); event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId); event GuardianTokensAssigned(address indexed guardian, uint256 amount); event GuardianTokensBurned(uint256 amount); event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId); event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit); /** * @dev Constructor function * @param _controller Address of the controller * @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry * @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry */ constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public { require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT); guardiansToken = _guardiansToken; _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); tree.init(); // First tree item is an empty guardian assert(tree.insert(0, 0) == 0); } /** * @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian to stake tokens to * @param _amount Amount of tokens to be staked */ function stake(address _guardian, uint256 _amount) external { _stake(_guardian, _amount); } /** * @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian` * @param _guardian Address of the guardian to unstake tokens from * @param _amount Amount of tokens to be unstaked */ function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _unstake(_guardian, _amount); } /** * @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian activating the tokens for * @param _amount Amount of guardian tokens to be activated for the next term */ function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _activate(_guardian, _amount); } /** * @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian deactivating the tokens for * @param _amount Amount of guardian tokens to be deactivated for the next term */ function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _deactivate(_guardian, _amount); } /** * @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian staking and activating tokens for * @param _amount Amount of tokens to be staked and activated */ function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _stake(_guardian, _amount); _activate(_guardian, _amount); } /** * @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian locking the activation for * @param _lockManager Address of the lock manager that will control the lock * @param _amount Amount of active tokens to be locked */ function lockActivation(address _guardian, address _lockManager, uint256 _amount) external { // Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian); // Make sure that the given lock manager is allowed require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED); _lockActivation(_guardian, _lockManager, _amount); } /** * @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian unlocking the active balance of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of active tokens to be unlocked * @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately */ function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 lockedAmount = activationLocks.lockedBy[_lockManager]; require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION); uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount; require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT); // Always allow the lock manager to unlock bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock); require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION); uint256 newLockedAmount = lockedAmount.sub(amountToUnlock); uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); // In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it if (_requestDeactivation) { _authenticateSender(_guardian); _deactivate(_guardian, _amount); } } /** * @notice Process a token deactivation requested for `_guardian` if there is any * @param _guardian Address of the guardian to process the deactivation request of */ function processDeactivationRequest(address _guardian) external { uint64 termId = _ensureCurrentTerm(); _processDeactivationRequest(_guardian, termId); } /** * @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian` * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(_guardian, _amount, true); emit GuardianTokensAssigned(_guardian, _amount); } } /** * @notice Burn `@tokenAmount(self.token(), _amount)` * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true); emit GuardianTokensBurned(_amount); } } /** * @notice Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) { DraftParams memory draftParams = _buildDraftParams(_params); guardians = new address[](draftParams.batchRequestedGuardians); // Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus, // we compute several sortitions until all the requested guardians are selected. To guarantee a different set of // guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition. // Note that we are capping the number of iterations to avoid an OOG error, which means that this function could // return less guardians than the requested number. for (draftParams.iteration = 0; length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS; draftParams.iteration++ ) { (uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams); for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) { // We assume the selected guardians are registered in the registry, we are not checking their addresses exist address guardianAddress = guardiansAddressById[guardianIds[i]]; Guardian storage guardian = guardiansByAddress[guardianAddress]; // Compute new locked balance for a guardian based on the penalty applied when being drafted uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount); // Check if there is any deactivation requests for the next term. Drafts are always computed for the current term // but we have to make sure we are locking an amount that will exist in the next term. uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1); // Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise. uint256 currentActiveBalance = activeBalances[i]; if (currentActiveBalance >= newLockedBalance) { // Check if the amount of active tokens for the next term is enough to lock the required amount for // the draft. Otherwise, reduce the requested deactivation amount of the next term. // Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount); if (nextTermActiveBalance < newLockedBalance) { // No need for SafeMath: we already checked values above _reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId); } // Update the current active locked balance of the guardian guardian.lockedBalance = newLockedBalance; guardians[length++] = guardianAddress; emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount); } } } } /** * @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the * corresponding locked balances of those guardians that are set to be slashed. * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external onlyActiveDisputeManager returns (uint256) { require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH); require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH); uint64 nextTermId = _termId + 1; uint256 collectedTokens; for (uint256 i = 0; i < _guardians.length; i++) { uint256 lockedAmount = _lockedAmounts[i]; address guardianAddress = _guardians[i]; Guardian storage guardian = guardiansByAddress[guardianAddress]; guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount); // Slash guardian if requested. Note that there's no need to check if there was a deactivation // request since we're working with already locked balances. if (_rewardedGuardians[i]) { emit GuardianBalanceUnlocked(guardianAddress, lockedAmount); } else { collectedTokens = collectedTokens.add(lockedAmount); tree.update(guardian.id, nextTermId, lockedAmount, false); emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId); } } return collectedTokens; } /** * @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`. * @dev This function tries to decrease the active balance of a guardian for the next term based on the requested * amount. It can be seen as a way to early-slash a guardian's active balance. * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) { if (_amount == 0) { return true; } uint64 nextTermId = _termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId); // Check if the guardian has enough unlocked tokens to collect the requested amount // Note that we're also considering the deactivation request if there is any uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount); if (_amount > totalUnlockedActiveBalance) { return false; } // Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of // the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect // of a guardian deliberately voting in a final round, while drafts occur randomly. if (_amount > unlockedActiveBalance) { // No need for SafeMath: amounts were already checked above uint256 amountToReduce = _amount - unlockedActiveBalance; _reduceDeactivationRequest(_guardian, amountToReduce, _termId); } tree.update(guardian.id, nextTermId, _amount, false); emit GuardianTokensCollected(_guardian, _amount, nextTermId); return true; } /** * @notice Lock `_guardian`'s withdrawals until term #`_termId` * @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager { Guardian storage guardian = guardiansByAddress[_guardian]; guardian.withdrawalsLockTermId = _termId; } /** * @notice Set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor { _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); } /** * @dev Tell the total supply of guardian tokens staked * @return Supply of guardian tokens staked */ function totalSupply() external view returns (uint256) { return guardiansToken.balanceOf(address(this)); } /** * @dev Tell the total amount of active guardian tokens * @return Total amount of active guardian tokens */ function totalActiveBalance() external view returns (uint256) { return tree.getTotal(); } /** * @dev Tell the total amount of active guardian tokens for a given term id * @param _termId Term ID to query on * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) { return _totalActiveBalanceAt(_termId); } /** * @dev Tell the total balance of tokens held by a guardian * This includes the active balance, the available balances, and the pending balance for deactivation. * Note that we don't have to include the locked balances since these represent the amount of active tokens * that are locked for drafts, i.e. these are already included in the active balance of the guardian. * @param _guardian Address of the guardian querying the balance of * @return Total amount of tokens of a guardian */ function balanceOf(address _guardian) external view returns (uint256) { return _balanceOf(_guardian); } /** * @dev Tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the detailed balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function detailedBalanceOf(address _guardian) external view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { return _detailedBalanceOf(_guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID to query on * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) { return _activeBalanceOfAt(_guardian, _termId); } /** * @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes * @param _guardian Address of the guardian querying the unlocked balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _currentUnlockedActiveBalanceOf(guardian); } /** * @dev Tell the pending deactivation details for a guardian * @param _guardian Address of the guardian whose info is requested * @return amount Amount to be deactivated * @return availableTermId Term in which the deactivated amount will be available */ function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) { DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest; return (request.amount, request.availableTermId); } /** * @dev Tell the activation amount locked for a guardian by a lock manager * @param _guardian Address of the guardian whose info is requested * @param _lockManager Address of the lock manager querying the lock of * @return amount Activation amount locked by the lock manager * @return total Total activation amount locked for the guardian */ function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; total = activationLocks.total; amount = activationLocks.lockedBy[_lockManager]; } /** * @dev Tell the withdrawals lock term ID for a guardian * @param _guardian Address of the guardian whose info is requested * @return Term ID until which the guardian's withdrawals will be locked */ function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) { return guardiansByAddress[_guardian].withdrawalsLockTermId; } /** * @dev Tell the identification number associated to a guardian address * @param _guardian Address of the guardian querying the identification number of * @return Identification number associated to a guardian address, zero in case it wasn't registered yet */ function getGuardianId(address _guardian) external view returns (uint256) { return guardiansByAddress[_guardian].id; } /** * @dev Internal function to activate a given amount of tokens for a guardian. * This function assumes that the given term is the current term and has already been ensured. * @param _guardian Address of the guardian to activate tokens * @param _amount Amount of guardian tokens to be activated */ function _activate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if any _processDeactivationRequest(_guardian, termId); uint256 availableBalance = guardiansByAddress[_guardian].availableBalance; uint256 amountToActivate = _amount == 0 ? availableBalance : _amount; require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT); uint64 nextTermId = termId + 1; _checkTotalActiveBalance(nextTermId, amountToActivate); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 minActiveBalance = _getMinActiveBalance(nextTermId); if (_existsGuardian(guardian)) { // Even though we are adding amounts, let's check the new active balance is greater than or equal to the // minimum active amount. Note that the guardian might have been slashed. uint256 activeBalance = tree.getItem(guardian.id); require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); tree.update(guardian.id, nextTermId, amountToActivate, true); } else { require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); guardian.id = tree.insert(nextTermId, amountToActivate); guardiansAddressById[guardian.id] = _guardian; } _updateAvailableBalanceOf(_guardian, amountToActivate, false); emit GuardianActivated(_guardian, nextTermId, amountToActivate); } /** * @dev Internal function to deactivate a given amount of tokens for a guardian. * @param _guardian Address of the guardian to deactivate tokens * @param _amount Amount of guardian tokens to be deactivated for the next term */ function _deactivate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount; require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); // Check future balance is not below the total activation lock of the guardian // No need for SafeMath: we already checked values above uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate; uint256 totalActivationLock = guardian.activationLocks.total; require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK); // Check that the guardian is leaving or that the minimum active balance is met uint256 minActiveBalance = _getMinActiveBalance(termId); require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); _createDeactivationRequest(_guardian, amountToDeactivate); } /** * @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed * to process a deactivation request from the next term. * @param _guardian Address of the guardian to create a token deactivation request for * @param _amount Amount of guardian tokens requested for deactivation */ function _createDeactivationRequest(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if possible _processDeactivationRequest(_guardian, termId); uint64 nextTermId = termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; request.amount = request.amount.add(_amount); request.availableTermId = nextTermId; tree.update(guardian.id, nextTermId, _amount, false); emit GuardianDeactivationRequested(_guardian, nextTermId, _amount); } /** * @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount * to the available balance of the guardian if the term when the deactivation was requested has already finished. * @param _guardian Address of the guardian to process the deactivation request of * @param _termId Current term id */ function _processDeactivationRequest(address _guardian, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint64 deactivationAvailableTermId = request.availableTermId; // If there is a deactivation request, ensure that the deactivation term has been reached if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) { return; } uint256 deactivationAmount = request.amount; // Note that we can use a zeroed term ID to denote void here since we are storing // the minimum allowed term to deactivate tokens which will always be at least 1. request.availableTermId = uint64(0); request.amount = 0; _updateAvailableBalanceOf(_guardian, deactivationAmount, true); emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId); } /** * @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request * cannot be processed for the given term yet. * @param _guardian Address of the guardian to reduce the deactivation request of * @param _amount Amount to be reduced from the current deactivation request * @param _termId Term ID in which the deactivation request is being reduced */ function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint256 currentRequestAmount = request.amount; require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST); // No need for SafeMath: we already checked values above uint256 newRequestAmount = currentRequestAmount - _amount; request.amount = newRequestAmount; // Move amount back to the tree tree.update(guardian.id, _termId + 1, _amount, true); emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId); } /** * @dev Internal function to update the activation locked amount of a guardian * @param _guardian Guardian to update the activation locked amount of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of tokens to be added to the activation locked amount of the guardian */ function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 newTotalLocked = activationLocks.total.add(_amount); uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); } /** * @dev Internal function to stake an amount of tokens for a guardian * @param _guardian Address of the guardian to deposit the tokens to * @param _amount Amount of tokens to be deposited */ function _stake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); _updateAvailableBalanceOf(_guardian, _amount, true); emit Staked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to unstake an amount of tokens of a guardian * @param _guardian Address of the guardian to to unstake the tokens of * @param _amount Amount of tokens to be unstaked */ function _unstake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); // Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure // the current term this time since deactivation requests always work with future terms, which means that if // the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here // to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks. uint64 lastEnsuredTermId = _getLastEnsuredTermId(); // Check that guardian's withdrawals are not locked uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId; require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK); _processDeactivationRequest(_guardian, lastEnsuredTermId); _updateAvailableBalanceOf(_guardian, _amount, false); emit Unstaked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to update the available balance of a guardian * @param _guardian Guardian to update the available balance of * @param _amount Amount of tokens to be added to or removed from the available balance of a guardian * @param _positive True if the given amount should be added, or false to remove it from the available balance */ function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal { // We are not using a require here to avoid reverting in case any of the treasury maths reaches this point // with a zeroed amount value. Instead, we are doing this validation in the external entry points such as // stake, unstake, activate, deactivate, among others. if (_amount == 0) { return; } Guardian storage guardian = guardiansByAddress[_guardian]; if (_positive) { guardian.availableBalance = guardian.availableBalance.add(_amount); } else { require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE); // No need for SafeMath: we already checked values right above guardian.availableBalance -= _amount; } } /** * @dev Internal function to set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal { require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT); emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit); totalActiveBalanceLimit = _totalActiveBalanceLimit; } /** * @dev Internal function to tell the total balance of tokens held by a guardian * @param _guardian Address of the guardian querying the total balance of * @return Total amount of tokens of a guardian */ function _balanceOf(address _guardian) internal view returns (uint256) { (uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian); return available.add(active).add(pendingDeactivation); } /** * @dev Internal function to tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _detailedBalanceOf(address _guardian) internal view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { Guardian storage guardian = guardiansByAddress[_guardian]; active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0; (available, locked, pendingDeactivation) = _getBalances(guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0; } /** * @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes * It will use the last value, that might be in a future term * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { uint64 lastEnsuredTermId = _getLastEnsuredTermId(); return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to check if a guardian was already registered * @param _guardian Guardian to be checked * @return True if the given guardian was already registered, false otherwise */ function _existsGuardian(Guardian storage _guardian) internal view returns (bool) { return _guardian.id != 0; } /** * @dev Internal function to get the amount of a deactivation request for a given term id * @param _guardian Guardian to query the deactivation request amount of * @param _termId Term ID of the deactivation request to be queried * @return Amount of the deactivation request for the given term, 0 otherwise */ function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) { DeactivationRequest storage request = _guardian.deactivationRequest; return request.availableTermId == _termId ? request.amount : 0; } /** * @dev Internal function to tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) { // This function will return always the same values, the only difference remains on gas costs. In case we look for a // recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint. // Otherwise, a binary search is computed. bool recent = _termId >= _getLastEnsuredTermId(); return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId); } /** * @dev Internal function to check if its possible to add a given new amount to the registry or not * @param _termId Term ID when the new amount will be added * @param _amount Amount of tokens willing to be added to the registry */ function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view { uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId); uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount); require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED); } /** * @dev Tell the local balance information of a guardian (that is not on the tree) * @param _guardian Address of the guardian querying the balance information of * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) { available = _guardian.availableBalance; locked = _guardian.lockedBalance; pendingDeactivation = _guardian.deactivationRequest.amount; } /** * @dev Internal function to search guardians in the tree based on certain search restrictions * @param _params Draft params to be used for the guardians search * @return ids List of guardian ids obtained based on the requested search * @return activeBalances List of active balances for each guardian obtained based on the requested search */ function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) { (ids, activeBalances) = tree.batchedRandomSearch( _params.termRandomness, _params.disputeId, _params.termId, _params.selectedGuardians, _params.batchRequestedGuardians, _params.roundRequestedGuardians, _params.iteration ); } /** * @dev Private function to parse a certain set given of draft params * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return Draft params object parsed */ function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) { uint64 termId = uint64(_params[2]); uint256 minActiveBalance = _getMinActiveBalance(termId); return DraftParams({ termRandomness: bytes32(_params[0]), disputeId: _params[1], termId: termId, selectedGuardians: _params[3], batchRequestedGuardians: _params[4], roundRequestedGuardians: _params[5], draftLockAmount: minActiveBalance.pct(uint16(_params[6])), iteration: 0 }); } }
Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian` _guardian Guardian to add an amount of tokens to _amount Amount of tokens to be added to the available balance of a guardian/
function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(_guardian, _amount, true); emit GuardianTokensAssigned(_guardian, _amount); } }
91,843
pragma solidity 0.4.24; /** * @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 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; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Escrow (based on openzeppelin version with one function to withdraw funds to the wallet) * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. * @return Amount withdrawn */ function withdraw(address _payee) public onlyOwner returns(uint256) { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); return payment; } /** * @dev Withdraws the wallet's funds. * @param _wallet address the funds will be transferred to. */ function beneficiaryWithdraw(address _wallet) public onlyOwner { uint256 _amount = address(this).balance; _wallet.transfer(_amount); emit Withdrawn(_wallet, _amount); } /** * @dev Returns the deposited amount of the given address. * @param _payee address of the payee of which to return the deposted amount. * @return Deposited amount by the address given as argument. */ function depositsOf(address _payee) public view returns(uint256) { return deposits[_payee]; } } /** * @title PullPayment (based on openzeppelin version with one function to withdraw funds to the wallet) * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncTransfer instead of send or transfer. */ contract PullPayment { Escrow private escrow; constructor() public { escrow = new Escrow(); } /** * @dev Returns the credit owed to an address. * @param _dest The creditor's address. * @return Deposited amount by the address given as argument. */ function payments(address _dest) public view returns(uint256) { return escrow.depositsOf(_dest); } /** * @dev Withdraw accumulated balance, called by payee. * @param _payee The address whose funds will be withdrawn and transferred to. * @return Amount withdrawn */ function _withdrawPayments(address _payee) internal returns(uint256) { uint256 payment = escrow.withdraw(_payee); return payment; } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param _dest The destination address of the funds. * @param _amount The amount to transfer. */ function _asyncTransfer(address _dest, uint256 _amount) internal { escrow.deposit.value(_amount)(_dest); } /** * @dev Withdraws the wallet's funds. * @param _wallet address the funds will be transferred to. */ function _withdrawFunds(address _wallet) internal { escrow.beneficiaryWithdraw(_wallet); } } /** @title VestedCrowdsale * @dev Extension of Crowdsale to allow a vested distribution of tokens * Users have to individually claim their tokens */ contract VestedCrowdsale { using SafeMath for uint256; mapping (address => uint256) public withdrawn; mapping (address => uint256) public contributions; mapping (address => uint256) public contributionsRound; uint256 public vestedTokens; /** * @dev Gives how much a user is allowed to withdraw at the current moment * @param _beneficiary The address of the user asking how much he's allowed * to withdraw * @return Amount _beneficiary is allowed to withdraw */ function getWithdrawableAmount(address _beneficiary) public view returns(uint256) { uint256 step = _getVestingStep(_beneficiary); uint256 valueByStep = _getValueByStep(_beneficiary); uint256 result = step.mul(valueByStep).sub(withdrawn[_beneficiary]); return result; } /** * @dev Gives the step of the vesting (starts from 0 to steps) * @param _beneficiary The address of the user asking how much he's allowed * to withdraw * @return The vesting step for _beneficiary */ function _getVestingStep(address _beneficiary) internal view returns(uint8) { require(contributions[_beneficiary] != 0); require(contributionsRound[_beneficiary] > 0 && contributionsRound[_beneficiary] < 4); uint256 march31 = 1554019200; uint256 april30 = 1556611200; uint256 may31 = 1559289600; uint256 june30 = 1561881600; uint256 july31 = 1564560000; uint256 sept30 = 1569830400; uint256 contributionRound = contributionsRound[_beneficiary]; // vesting for private sale contributors if (contributionRound == 1) { if (block.timestamp < march31) { return 0; } if (block.timestamp < june30) { return 1; } if (block.timestamp < sept30) { return 2; } return 3; } // vesting for pre ico contributors if (contributionRound == 2) { if (block.timestamp < april30) { return 0; } if (block.timestamp < july31) { return 1; } return 2; } // vesting for ico contributors if (contributionRound == 3) { if (block.timestamp < may31) { return 0; } return 1; } } /** * @dev Gives the amount a user is allowed to withdraw by step * @param _beneficiary The address of the user asking how much he's allowed * to withdraw * @return How much a user is allowed to withdraw by step */ function _getValueByStep(address _beneficiary) internal view returns(uint256) { require(contributions[_beneficiary] != 0); require(contributionsRound[_beneficiary] > 0 && contributionsRound[_beneficiary] < 4); uint256 contributionRound = contributionsRound[_beneficiary]; uint256 amount; uint256 rate; if (contributionRound == 1) { rate = 416700; amount = contributions[_beneficiary].mul(rate).mul(25).div(100); return amount; } else if (contributionRound == 2) { rate = 312500; amount = contributions[_beneficiary].mul(rate).mul(25).div(100); return amount; } rate = 250000; amount = contributions[_beneficiary].mul(rate).mul(25).div(100); return amount; } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { // Whitelisted address mapping(address => bool) public whitelist; event AddedBeneficiary(address indexed _beneficiary); event RemovedBeneficiary(address indexed _beneficiary); /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addAddressToWhitelist(address[] _beneficiaries) public onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; emit AddedBeneficiary(_beneficiaries[i]); } } /** * @dev Adds list of address to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = true; emit AddedBeneficiary(_beneficiary); } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = false; emit RemovedBeneficiary(_beneficiary); } } /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, 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); _; } /** * @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 onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @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) public view returns (uint256) { return _balances[owner]; } /** * @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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @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); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } /** * @title DSLACrowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether */ contract DSLACrowdsale is VestedCrowdsale, Whitelist, Pausable, PullPayment { // struct to store ico rounds details struct IcoRound { uint256 rate; uint256 individualFloor; uint256 individualCap; uint256 softCap; uint256 hardCap; } // mapping ico rounds mapping (uint256 => IcoRound) public icoRounds; // The token being sold ERC20Burnable private _token; // Address where funds are collected address private _wallet; // Amount of wei raised uint256 private totalContributionAmount; // Tokens to sell = 5 Billions * 10^18 = 5 * 10^27 = 5000000000000000000000000000 uint256 public constant TOKENSFORSALE = 5000000000000000000000000000; // Current ico round uint256 public currentIcoRound; // Distributed Tokens uint256 public distributedTokens; // Amount of wei raised from other currencies uint256 public weiRaisedFromOtherCurrencies; // Refund period on bool public isRefunding = false; // Finalized crowdsale off bool public isFinalized = false; // Refunding deadline uint256 public refundDeadline; /** * 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 TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(address wallet, ERC20Burnable token) public { require(wallet != address(0) && token != address(0)); icoRounds[1] = IcoRound( 416700, 3 ether, 600 ether, 0, 1200 ether ); icoRounds[2] = IcoRound( 312500, 12 ether, 5000 ether, 0, 6000 ether ); icoRounds[3] = IcoRound( 250000, 3 ether, 30 ether, 7200 ether, 17200 ether ); _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _contributor Address performing the token purchase */ function buyTokens(address _contributor) public payable { require(whitelist[_contributor]); uint256 contributionAmount = msg.value; _preValidatePurchase(_contributor, contributionAmount, currentIcoRound); totalContributionAmount = totalContributionAmount.add(contributionAmount); uint tokenAmount = _handlePurchase(contributionAmount, currentIcoRound, _contributor); emit TokensPurchased(msg.sender, _contributor, contributionAmount, tokenAmount); _forwardFunds(); } /** * @dev Function to go to the next round * @return True bool when round is incremented */ function goToNextRound() public onlyOwner returns(bool) { require(currentIcoRound >= 0 && currentIcoRound < 3); currentIcoRound = currentIcoRound + 1; return true; } /** * @dev Manually adds a contributor's contribution for private presale period * @param _contributor The address of the contributor * @param _contributionAmount Amount of wei contributed */ function addPrivateSaleContributors(address _contributor, uint256 _contributionAmount) public onlyOwner { uint privateSaleRound = 1; _preValidatePurchase(_contributor, _contributionAmount, privateSaleRound); totalContributionAmount = totalContributionAmount.add(_contributionAmount); addToWhitelist(_contributor); _handlePurchase(_contributionAmount, privateSaleRound, _contributor); } /** * @dev Manually adds a contributor's contribution with other currencies * @param _contributor The address of the contributor * @param _contributionAmount Amount of wei contributed * @param _round contribution round */ function addOtherCurrencyContributors(address _contributor, uint256 _contributionAmount, uint256 _round) public onlyOwner { _preValidatePurchase(_contributor, _contributionAmount, _round); weiRaisedFromOtherCurrencies = weiRaisedFromOtherCurrencies.add(_contributionAmount); addToWhitelist(_contributor); _handlePurchase(_contributionAmount, _round, _contributor); } /** * @dev Function to close refunding period * @return True bool */ function closeRefunding() public returns(bool) { require(isRefunding); require(block.timestamp > refundDeadline); isRefunding = false; _withdrawFunds(wallet()); return true; } /** * @dev Function to close the crowdsale * @return True bool */ function closeCrowdsale() public onlyOwner returns(bool) { require(currentIcoRound > 0 && currentIcoRound < 4); currentIcoRound = 4; return true; } /** * @dev Function to finalize the crowdsale * @param _burn bool burn unsold tokens when true * @return True bool */ function finalizeCrowdsale(bool _burn) public onlyOwner returns(bool) { require(currentIcoRound == 4 && !isRefunding); if (raisedFunds() < icoRounds[3].softCap) { isRefunding = true; refundDeadline = block.timestamp + 4 weeks; return true; } require(!isFinalized); _withdrawFunds(wallet()); isFinalized = true; if (_burn) { _burnUnsoldTokens(); } else { _withdrawUnsoldTokens(); } return true; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isRefunding); require(block.timestamp <= refundDeadline); require(payments(msg.sender) > 0); uint256 payment = _withdrawPayments(msg.sender); totalContributionAmount = totalContributionAmount.sub(payment); } /** * @dev Allows the sender to claim the tokens he is allowed to withdraw */ function claimTokens() public { require(getWithdrawableAmount(msg.sender) != 0); uint256 amount = getWithdrawableAmount(msg.sender); withdrawn[msg.sender] = withdrawn[msg.sender].add(amount); _deliverTokens(msg.sender, amount); } /** * @dev returns the token being sold * @return the token being sold */ function token() public view returns(ERC20Burnable) { return _token; } /** * @dev returns the wallet address that collects the funds * @return the address where funds are collected */ function wallet() public view returns(address) { return _wallet; } /** * @dev Returns the total of raised funds * @return total amount of raised funds */ function raisedFunds() public view returns(uint256) { return totalContributionAmount.add(weiRaisedFromOtherCurrencies); } // ----------------------------------------- // Internal interface // ----------------------------------------- /** * @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 Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { if (currentIcoRound == 2 || currentIcoRound == 3) { _asyncTransfer(msg.sender, msg.value); } else { _wallet.transfer(msg.value); } } /** * @dev Gets tokens allowed to deliver in the given round * @param _tokenAmount total amount of tokens involved in the purchase * @param _round Round in which the purchase is happening * @return Returns the amount of tokens allowed to deliver */ function _getTokensToDeliver(uint _tokenAmount, uint _round) internal pure returns(uint) { require(_round > 0 && _round < 4); uint deliverPercentage = _round.mul(25); return _tokenAmount.mul(deliverPercentage).div(100); } /** * @dev Handles token purchasing * @param _contributor Address performing the token purchase * @param _contributionAmount Value in wei involved in the purchase * @param _round Round in which the purchase is happening * @return Returns the amount of tokens purchased */ function _handlePurchase(uint _contributionAmount, uint _round, address _contributor) internal returns(uint) { uint256 soldTokens = distributedTokens.add(vestedTokens); uint256 tokenAmount = _getTokenAmount(_contributionAmount, _round); require(tokenAmount.add(soldTokens) <= TOKENSFORSALE); contributions[_contributor] = contributions[_contributor].add(_contributionAmount); contributionsRound[_contributor] = _round; uint tokensToDeliver = _getTokensToDeliver(tokenAmount, _round); uint tokensToVest = tokenAmount.sub(tokensToDeliver); distributedTokens = distributedTokens.add(tokensToDeliver); vestedTokens = vestedTokens.add(tokensToVest); _deliverTokens(_contributor, tokensToDeliver); return tokenAmount; } /** * @dev Validation of an incoming purchase. * @param _contributor Address performing the token purchase * @param _contributionAmount Value in wei involved in the purchase * @param _round Round in which the purchase is happening */ function _preValidatePurchase(address _contributor, uint256 _contributionAmount, uint _round) internal view { require(_contributor != address(0)); require(currentIcoRound > 0 && currentIcoRound < 4); require(_round > 0 && _round < 4); require(contributions[_contributor] == 0); require(_contributionAmount >= icoRounds[_round].individualFloor); require(_contributionAmount < icoRounds[_round].individualCap); require(_doesNotExceedHardCap(_contributionAmount, _round)); } /** * @dev define the way in which ether is converted to tokens. * @param _contributionAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _contributionAmount */ function _getTokenAmount(uint256 _contributionAmount, uint256 _round) internal view returns(uint256) { uint256 _rate = icoRounds[_round].rate; return _contributionAmount.mul(_rate); } /** * @dev Checks if current round hardcap will not be exceeded by a new contribution * @param _contributionAmount purchase amount in Wei * @param _round Round in which the purchase is happening * @return true when current hardcap is not exceeded, false if exceeded */ function _doesNotExceedHardCap(uint _contributionAmount, uint _round) internal view returns(bool) { uint roundHardCap = icoRounds[_round].hardCap; return totalContributionAmount.add(_contributionAmount) <= roundHardCap; } /** * @dev Function to burn unsold tokens */ function _burnUnsoldTokens() internal { uint256 tokensToBurn = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens); _token.burn(tokensToBurn); } /** * @dev Transfer the unsold tokens to the funds collecting address */ function _withdrawUnsoldTokens() internal { uint256 tokensToWithdraw = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens); _token.transfer(_wallet, tokensToWithdraw); } }
Function to burn unsold tokens/
function _burnUnsoldTokens() internal { uint256 tokensToBurn = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens); _token.burn(tokensToBurn); }
12,543,454
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; } } 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 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) { uint256 c = a + b; assert(c >= a); return c; } } library Utils { /* Not secured random number generation, but it's enough for the perpose of implementaion particular case*/ function almostRnd(uint min, uint max) internal view returns(uint) { return uint(keccak256(block.timestamp, block.blockhash(block.number))) % (max - min) + min; } } contract EternalStorage { /**** Storage Types *******/ address public owner; mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => uint8) private uInt8Storage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; mapping(bytes32 => bytes32) private bytes32Storage; /*** Modifiers ************/ /// @dev Only allow access from the latest version of a contract in the Rocket Pool network after deployment modifier onlyLatestContract() { require(addressStorage[keccak256("contract.address", msg.sender)] != 0x0 || msg.sender == owner); _; } /// @dev constructor function EternalStorage() public { owner = msg.sender; addressStorage[keccak256("contract.address", msg.sender)] = msg.sender; } function setOwner() public { require(msg.sender == owner); addressStorage[keccak256("contract.address", owner)] = 0x0; owner = msg.sender; addressStorage[keccak256("contract.address", msg.sender)] = msg.sender; } /**** Get Methods ***********/ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } /// @param _key The key for the record function getUint8(bytes32 _key) external view returns (uint8) { return uInt8Storage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } /// @param _key The key for the record function getBytes32(bytes32 _key) external view returns (bytes32) { return bytes32Storage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /**** Set Methods ***********/ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyLatestContract external { addressStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyLatestContract external { uIntStorage[_key] = _value; } /// @param _key The key for the record function setUint8(bytes32 _key, uint8 _value) onlyLatestContract external { uInt8Storage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyLatestContract external { stringStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyLatestContract external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setBytes32(bytes32 _key, bytes32 _value) onlyLatestContract external { bytes32Storage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyLatestContract external { boolStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyLatestContract external { intStorage[_key] = _value; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyLatestContract external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyLatestContract external { delete uIntStorage[_key]; } /// @param _key The key for the record function deleteUint8(bytes32 _key) onlyLatestContract external { delete uInt8Storage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyLatestContract external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyLatestContract external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteBytes32(bytes32 _key) onlyLatestContract external { delete bytes32Storage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyLatestContract external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyLatestContract external { delete intStorage[_key]; } } contract EIP20 { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Token { function balanceOf(address owner) public view returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public view returns (uint256 remaining); } contract IBoardConfig is Ownable { uint constant decimals = 10 ** uint(18); uint8 public version; function resetValuesToDefault() external; function setStorageAddress(address storageAddress) external; function getRefereeFee() external view returns (uint); function getRefereeFeeEth() external view returns(uint); function getVoteTokenPrice() external view returns (uint); function setVoteTokenPrice(uint value) external; function getVoteTokenPriceEth() external view returns (uint); function setVoteTokenPriceEth(uint value) external; function getVoteTokensPerRequest() external view returns (uint); function setVoteTokensPerRequest(uint voteTokens) external; function getTimeToStartVotingCase() external view returns (uint); function setTimeToStartVotingCase(uint value) external; function getTimeToRevealVotesCase() external view returns (uint); function setTimeToRevealVotesCase(uint value) external; function getTimeToCloseCase() external view returns (uint); function setTimeToCloseCase(uint value) external; function getRefereeCountPerCase() external view returns(uint); function setRefereeCountPerCase(uint refereeCount) external; function getRefereeNeedCountPerCase() external view returns(uint); function setRefereeNeedCountPerCase(uint refereeCount) external; function getFullConfiguration() external view returns( uint voteTokenPrice, uint voteTokenPriceEth, uint voteTokenPerRequest, uint refereeCountPerCase, uint refereeNeedCountPerCase, uint timeToStartVoting, uint timeToRevealVotes, uint timeToClose ); function getCaseDatesFromNow() public view returns(uint[] dates); } library RefereeCasesLib { function setRefereesToCase(address storageAddress, address[] referees, bytes32 caseId) public { for (uint i = 0; i < referees.length; i++) { setRefereeToCase(storageAddress, referees[i], caseId, i); } setRefereeCountForCase(storageAddress, caseId, referees.length); } function isRefereeVoted(address storageAddress, address referee, bytes32 caseId) public view returns (bool) { return EternalStorage(storageAddress).getBool(keccak256("case.referees.voted", caseId, referee)); } function setRefereeVote(address storageAddress, bytes32 caseId, address referee, bool forApplicant) public { uint index = getRefereeVotesFor(storageAddress, caseId, forApplicant); EternalStorage(storageAddress).setAddress(keccak256("case.referees.vote", caseId, forApplicant, index), referee); setRefereeVotesFor(storageAddress, caseId, forApplicant, index + 1); } function getRefereeVoteForByIndex(address storageAddress, bytes32 caseId, bool forApplicant, uint index) public view returns (address) { return EternalStorage(storageAddress).getAddress(keccak256("case.referees.vote", caseId, forApplicant, index)); } function getRefereeVotesFor(address storageAddress, bytes32 caseId, bool forApplicant) public view returns (uint) { return EternalStorage(storageAddress).getUint(keccak256("case.referees.votes.count", caseId, forApplicant)); } function setRefereeVotesFor(address storageAddress, bytes32 caseId, bool forApplicant, uint votes) public { EternalStorage(storageAddress).setUint(keccak256("case.referees.votes.count", caseId, forApplicant), votes); } function getRefereeCountByCase(address storageAddress, bytes32 caseId) public view returns (uint) { return EternalStorage(storageAddress).getUint(keccak256("case.referees.count", caseId)); } function setRefereeCountForCase(address storageAddress, bytes32 caseId, uint value) public { EternalStorage(storageAddress).setUint(keccak256("case.referees.count", caseId), value); } function getRefereeByCase(address storageAddress, bytes32 caseId, uint index) public view returns (address) { return EternalStorage(storageAddress).getAddress(keccak256("case.referees", caseId, index)); } function isRefereeSetToCase(address storageAddress, address referee, bytes32 caseId) public view returns(bool) { return EternalStorage(storageAddress).getBool(keccak256("case.referees", caseId, referee)); } function setRefereeToCase(address storageAddress, address referee, bytes32 caseId, uint index) public { EternalStorage st = EternalStorage(storageAddress); st.setAddress(keccak256("case.referees", caseId, index), referee); st.setBool(keccak256("case.referees", caseId, referee), true); } function getRefereeVoteHash(address storageAddress, bytes32 caseId, address referee) public view returns (bytes32) { return EternalStorage(storageAddress).getBytes32(keccak256("case.referees.vote.hash", caseId, referee)); } function setRefereeVoteHash(address storageAddress, bytes32 caseId, address referee, bytes32 voteHash) public { uint caseCount = getRefereeVoteHashCount(storageAddress, caseId); EternalStorage(storageAddress).setBool(keccak256("case.referees.voted", caseId, referee), true); EternalStorage(storageAddress).setBytes32(keccak256("case.referees.vote.hash", caseId, referee), voteHash); EternalStorage(storageAddress).setUint(keccak256("case.referees.vote.hash.count", caseId), caseCount + 1); } function getRefereeVoteHashCount(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.referees.vote.hash.count", caseId)); } function getRefereesFor(address storageAddress, bytes32 caseId, bool forApplicant) public view returns(address[]) { uint n = getRefereeVotesFor(storageAddress, caseId, forApplicant); address[] memory referees = new address[](n); for (uint i = 0; i < n; i++) { referees[i] = getRefereeVoteForByIndex(storageAddress, caseId, forApplicant, i); } return referees; } function getRefereesByCase(address storageAddress, bytes32 caseId) public view returns (address[]) { uint n = getRefereeCountByCase(storageAddress, caseId); address[] memory referees = new address[](n); for (uint i = 0; i < n; i++) { referees[i] = getRefereeByCase(storageAddress, caseId, i); } return referees; } } contract Withdrawable is Ownable { function withdrawEth(uint value) external onlyOwner { require(address(this).balance >= value); msg.sender.transfer(value); } function withdrawToken(address token, uint value) external onlyOwner { require(Token(token).balanceOf(address(this)) >= value, "Not enough tokens"); require(Token(token).transfer(msg.sender, value)); } } library CasesLib { enum CaseStatus {OPENED, VOTING, REVEALING, CLOSED, CANCELED} enum CaseCanceledCode { NOT_ENOUGH_VOTES, EQUAL_NUMBER_OF_VOTES } function getCase(address storageAddress, bytes32 caseId) public view returns ( address applicant, address respondent, bytes32 deal, uint amount, uint refereeAward, bytes32 title, uint8 status, uint8 canceledCode, bool won, bytes32 applicantDescriptionHash, bytes32 respondentDescriptionHash, bool isEthRefereeAward) { EternalStorage st = EternalStorage(storageAddress); applicant = st.getAddress(keccak256("case.applicant", caseId)); respondent = st.getAddress(keccak256("case.respondent", caseId)); deal = st.getBytes32(keccak256("case.deal", caseId)); amount = st.getUint(keccak256("case.amount", caseId)); won = st.getBool(keccak256("case.won", caseId)); status = st.getUint8(keccak256("case.status", caseId)); canceledCode = st.getUint8(keccak256("case.canceled.cause.code", caseId)); refereeAward = st.getUint(keccak256("case.referee.award", caseId)); title = st.getBytes32(keccak256("case.title", caseId)); applicantDescriptionHash = st.getBytes32(keccak256("case.applicant.description", caseId)); respondentDescriptionHash = st.getBytes32(keccak256("case.respondent.description", caseId)); isEthRefereeAward = st.getBool(keccak256("case.referee.award.eth", caseId)); } function getCaseDates(address storageAddress, bytes32 caseId) public view returns (uint date, uint votingDate, uint revealingDate, uint closeDate) { EternalStorage st = EternalStorage(storageAddress); date = st.getUint(keccak256("case.date", caseId)); votingDate = st.getUint(keccak256("case.date.voting", caseId)); revealingDate = st.getUint(keccak256("case.date.revealing", caseId)); closeDate = st.getUint(keccak256("case.date.close", caseId)); } function addCase( address storageAddress, address applicant, address respondent, bytes32 deal, uint amount, uint refereeAward, bytes32 title, string applicantDescription, uint[] dates, uint refereeCountNeed, bool isEthRefereeAward ) public returns(bytes32 caseId) { EternalStorage st = EternalStorage(storageAddress); caseId = keccak256(applicant, respondent, deal, dates[0], title, amount); st.setAddress(keccak256("case.applicant", caseId), applicant); st.setAddress(keccak256("case.respondent", caseId), respondent); st.setBytes32(keccak256("case.deal", caseId), deal); st.setUint(keccak256("case.amount", caseId), amount); st.setUint(keccak256("case.date", caseId), dates[0]); st.setUint(keccak256("case.date.voting", caseId), dates[1]); st.setUint(keccak256("case.date.revealing", caseId), dates[2]); st.setUint(keccak256("case.date.close", caseId), dates[3]); st.setUint8(keccak256("case.status", caseId), 0);//OPENED st.setUint(keccak256("case.referee.award", caseId), refereeAward); st.setBytes32(keccak256("case.title", caseId), title); st.setBytes32(keccak256("case.applicant.description", caseId), keccak256(applicantDescription)); st.setBool(keccak256("case.referee.award.eth", caseId), isEthRefereeAward); st.setUint(keccak256("case.referee.count.need", caseId), refereeCountNeed); } function setCaseWon(address storageAddress, bytes32 caseId, bool won) public { EternalStorage st = EternalStorage(storageAddress); st.setBool(keccak256("case.won", caseId), won); } function setCaseStatus(address storageAddress, bytes32 caseId, CaseStatus status) public { uint8 statusCode = uint8(status); require(statusCode >= 0 && statusCode <= uint8(CaseStatus.CANCELED)); EternalStorage(storageAddress).setUint8(keccak256("case.status", caseId), statusCode); } function getCaseStatus(address storageAddress, bytes32 caseId) public view returns(CaseStatus) { return CaseStatus(EternalStorage(storageAddress).getUint8(keccak256("case.status", caseId))); } function setCaseCanceledCode(address storageAddress, bytes32 caseId, CaseCanceledCode cause) public { uint8 causeCode = uint8(cause); require(causeCode >= 0 && causeCode <= uint8(CaseCanceledCode.EQUAL_NUMBER_OF_VOTES)); EternalStorage(storageAddress).setUint8(keccak256("case.canceled.cause.code", caseId), causeCode); } function getCaseDate(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.date", caseId)); } function getRespondentDescription(address storageAddress, bytes32 caseId) public view returns(bytes32) { return EternalStorage(storageAddress).getBytes32(keccak256("case.respondent.description", caseId)); } function setRespondentDescription(address storageAddress, bytes32 caseId, string description) public { EternalStorage(storageAddress).setBytes32(keccak256("case.respondent.description", caseId), keccak256(description)); } function getApplicant(address storageAddress, bytes32 caseId) public view returns(address) { return EternalStorage(storageAddress).getAddress(keccak256("case.applicant", caseId)); } function getRespondent(address storageAddress, bytes32 caseId) public view returns(address) { return EternalStorage(storageAddress).getAddress(keccak256("case.respondent", caseId)); } function getRefereeAward(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.referee.award", caseId)); } function getVotingDate(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.date.voting", caseId)); } function getRevealingDate(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.date.revealing", caseId)); } function getCloseDate(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.date.close", caseId)); } function getRefereeCountNeed(address storageAddress, bytes32 caseId) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("case.referee.count.need", caseId)); } function isEthRefereeAward(address storageAddress, bytes32 caseId) public view returns(bool) { return EternalStorage(storageAddress).getBool(keccak256("case.referee.award.eth", caseId)); } } library VoteTokenLib { function getVotes(address storageAddress, address account) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("vote.token.balance", account)); } function increaseVotes(address storageAddress, address account, uint256 diff) public { setVotes(storageAddress, account, getVotes(storageAddress, account) + diff); } function decreaseVotes(address storageAddress, address account, uint256 diff) public { setVotes(storageAddress, account, getVotes(storageAddress, account) - diff); } function setVotes(address storageAddress, address account, uint256 value) public { EternalStorage(storageAddress).setUint(keccak256("vote.token.balance", account), value); } } contract PaymentHolder is Ownable { modifier onlyAllowed() { require(allowed[msg.sender]); _; } modifier onlyUpdater() { require(msg.sender == updater); _; } mapping(address => bool) public allowed; address public updater; /*-----------------MAINTAIN METHODS------------------*/ function setUpdater(address _updater) external onlyOwner { updater = _updater; } function migrate(address newHolder, address[] tokens, address[] _allowed) external onlyOwner { require(PaymentHolder(newHolder).update.value(address(this).balance)(_allowed)); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; uint256 balance = Token(token).balanceOf(this); if (balance > 0) { require(Token(token).transfer(newHolder, balance)); } } } function update(address[] _allowed) external payable onlyUpdater returns(bool) { for (uint256 i = 0; i < _allowed.length; i++) { allowed[_allowed[i]] = true; } return true; } /*-----------------OWNER FLOW------------------*/ function allow(address to) external onlyOwner { allowed[to] = true; } function prohibit(address to) external onlyOwner { allowed[to] = false; } /*-----------------ALLOWED FLOW------------------*/ function depositEth() public payable onlyAllowed returns (bool) { //Default function to receive eth return true; } function withdrawEth(address to, uint256 amount) public onlyAllowed returns(bool) { require(address(this).balance >= amount, "Not enough ETH balance"); to.transfer(amount); return true; } function withdrawToken(address to, uint256 amount, address token) public onlyAllowed returns(bool) { require(Token(token).balanceOf(this) >= amount, "Not enough token balance"); require(Token(token).transfer(to, amount)); return true; } } library RefereesLib { struct Referees { address[] addresses; } function addReferee(address storageAddress, address referee) public { uint id = getRefereeCount(storageAddress); setReferee(storageAddress, referee, id, true); setRefereeCount(storageAddress, id + 1); } function getRefereeCount(address storageAddress) public view returns(uint) { return EternalStorage(storageAddress).getUint(keccak256("referee.count")); } function setRefereeCount(address storageAddress, uint value) public { EternalStorage(storageAddress).setUint(keccak256("referee.count"), value); } function setReferee(address storageAddress, address referee, uint id, bool applied) public { EternalStorage st = EternalStorage(storageAddress); st.setBool(keccak256("referee.applied", referee), applied); st.setAddress(keccak256("referee.address", id), referee); } function isRefereeApplied(address storageAddress, address referee) public view returns(bool) { return EternalStorage(storageAddress).getBool(keccak256("referee.applied", referee)); } function setRefereeApplied(address storageAddress, address referee, bool applied) public { EternalStorage(storageAddress).setBool(keccak256("referee.applied", referee), applied); } function getRefereeAddress(address storageAddress, uint id) public view returns(address) { return EternalStorage(storageAddress).getAddress(keccak256("referee.address", id)); } function getRandomRefereesToCase(address storageAddress, address applicant, address respondent, uint256 targetCount) public view returns(address[] foundReferees) { uint refereesCount = getRefereeCount(storageAddress); require(refereesCount >= targetCount); foundReferees = new address[](targetCount); uint id = Utils.almostRnd(0, refereesCount); uint found = 0; for (uint i = 0; i < refereesCount; i++) { address referee = getRefereeAddress(storageAddress, id); id = id + 1; id = id % refereesCount; uint voteBalance = VoteTokenLib.getVotes(storageAddress, referee); if (referee != applicant && referee != respondent && voteBalance > 0) { foundReferees[found] = referee; found++; } if (found == targetCount) { break; } } require(found == targetCount); } } contract BkxToken is EIP20 { function increaseApproval (address _spender, uint _addedValue) public returns (bool success); function decreaseApproval (address _spender, uint _subtractedValue)public returns (bool success); } contract IBoard is Ownable { event CaseOpened(bytes32 caseId, address applicant, address respondent, bytes32 deal, uint amount, uint refereeAward, bytes32 title, string applicantDescription, uint[] dates, uint refereeCountNeed, bool isEthRefereeAward); event CaseCommentedByRespondent(bytes32 caseId, address respondent, string comment); event CaseVoting(bytes32 caseId); event CaseVoteCommitted(bytes32 caseId, address referee, bytes32 voteHash); event CaseRevealingVotes(bytes32 caseId); event CaseVoteRevealed(bytes32 caseId, address referee, uint8 voteOption, bytes32 salt); event CaseClosed(bytes32 caseId, bool won); event CaseCanceled(bytes32 caseId, uint8 causeCode); event RefereesAssignedToCase(bytes32 caseId, address[] referees); event RefereeVoteBalanceChanged(address referee, uint balance); event RefereeAwarded(address referee, bytes32 caseId, uint award); address public lib; uint public version; IBoardConfig public config; BkxToken public bkxToken; address public admin; address public paymentHolder; modifier onlyOwnerOrAdmin() { require(msg.sender == admin || msg.sender == owner); _; } function withdrawEth(uint value) external; function withdrawBkx(uint value) external; function setStorageAddress(address storageAddress) external; function setConfigAddress(address configAddress) external; function setBkxToken(address tokenAddress) external; function setPaymentHolder(address paymentHolder) external; function setAdmin(address admin) external; function applyForReferee() external payable; function addVoteTokens(address referee) external; function openCase(address respondent, bytes32 deal, uint amount, uint refereeAward, bytes32 title, string description) external payable; function setRespondentDescription(bytes32 caseId, string description) external; function startVotingCase(bytes32 caseId) external; function createVoteHash(uint8 voteOption, bytes32 salt) public view returns(bytes32); function commitVote(bytes32 caseId, bytes32 voteHash) external; function verifyVote(bytes32 caseId, address referee, uint8 voteOption, bytes32 salt) public view returns(bool); function startRevealingVotes(bytes32 caseId) external; function revealVote(bytes32 caseId, address referee, uint8 voteOption, bytes32 salt) external; function revealVotes(bytes32 caseId, address[] referees, uint8[] voteOptions, bytes32[] salts) external; function verdict(bytes32 caseId) external; } contract Board is IBoard { using SafeMath for uint; using VoteTokenLib for address; using CasesLib for address; using RefereesLib for address; using RefereeCasesLib for address; modifier onlyRespondent(bytes32 caseId) { require(msg.sender == lib.getRespondent(caseId)); _; } modifier hasStatus(bytes32 caseId, CasesLib.CaseStatus state) { require(state == lib.getCaseStatus(caseId)); _; } modifier before(uint date) { require(now <= date); _; } modifier laterOn(uint date) { require(now >= date); _; } function Board(address storageAddress, address configAddress, address _paymentHolder) public { version = 2; config = IBoardConfig(configAddress); lib = storageAddress; //check real BKX address https://etherscan.io/token/0x45245bc59219eeaAF6cD3f382e078A461FF9De7B bkxToken = BkxToken(0x45245bc59219eeaAF6cD3f382e078A461FF9De7B); admin = 0xE0b6C095D722961C2C11E55b97fCd0C8bd7a1cD2; paymentHolder = _paymentHolder; } function withdrawEth(uint value) external onlyOwner { require(address(this).balance >= value); msg.sender.transfer(value); } function withdrawBkx(uint value) external onlyOwner { require(bkxToken.balanceOf(address(this)) >= value); require(bkxToken.transfer(msg.sender, value)); } /* configuration */ function setStorageAddress(address storageAddress) external onlyOwner { lib = storageAddress; } function setConfigAddress(address configAddress) external onlyOwner { config = IBoardConfig(configAddress); } /* dependency tokens */ function setBkxToken(address tokenAddress) external onlyOwner { bkxToken = BkxToken(tokenAddress); } function setPaymentHolder(address _paymentHolder) external onlyOwner { paymentHolder = _paymentHolder; } function setAdmin(address newAdmin) external onlyOwner { admin = newAdmin; } function applyForReferee() external payable { uint refereeFee = msg.value == 0 ? config.getRefereeFee() : config.getRefereeFeeEth(); withdrawPayment(refereeFee); addVotes(msg.sender); } function addVoteTokens(address referee) external onlyOwnerOrAdmin { addVotes(referee); } function addVotes(address referee) private { uint refereeTokens = config.getVoteTokensPerRequest(); if (!lib.isRefereeApplied(referee)) { lib.addReferee(referee); } uint balance = refereeTokens.add(lib.getVotes(referee)); lib.setVotes(referee, balance); emit RefereeVoteBalanceChanged(referee, balance); } function openCase(address respondent, bytes32 deal, uint amount, uint refereeAward, bytes32 title, string description) external payable { require(msg.sender != respondent); withdrawPayment(refereeAward); uint[] memory dates = config.getCaseDatesFromNow(); uint refereeCountNeed = config.getRefereeNeedCountPerCase(); bytes32 caseId = lib.addCase(msg.sender, respondent, deal, amount, refereeAward, title, description, dates, refereeCountNeed, msg.value != 0); emit CaseOpened(caseId, msg.sender, respondent, deal, amount, refereeAward, title, description, dates, refereeCountNeed, msg.value != 0); assignRefereesToCase(caseId, msg.sender, respondent); } function withdrawPayment(uint256 amount) private { if(msg.value != 0) { require(msg.value == amount, "ETH amount must be equal amount"); require(PaymentHolder(paymentHolder).depositEth.value(msg.value)()); } else { require(bkxToken.allowance(msg.sender, address(this)) >= amount); require(bkxToken.balanceOf(msg.sender) >= amount); require(bkxToken.transferFrom(msg.sender, paymentHolder, amount)); } } function assignRefereesToCase(bytes32 caseId, address applicant, address respondent) private { uint targetCount = config.getRefereeCountPerCase(); address[] memory foundReferees = lib.getRandomRefereesToCase(applicant, respondent, targetCount); for (uint i = 0; i < foundReferees.length; i++) { address referee = foundReferees[i]; uint voteBalance = lib.getVotes(referee); voteBalance -= 1; lib.setVotes(referee, voteBalance); emit RefereeVoteBalanceChanged(referee, voteBalance); } lib.setRefereesToCase(foundReferees, caseId); emit RefereesAssignedToCase(caseId, foundReferees); } function setRespondentDescription(bytes32 caseId, string description) external onlyRespondent(caseId) hasStatus(caseId, CasesLib.CaseStatus.OPENED) before(lib.getVotingDate(caseId)) { require(lib.getRespondentDescription(caseId) == 0); lib.setRespondentDescription(caseId, description); lib.setCaseStatus(caseId, CasesLib.CaseStatus.VOTING); emit CaseCommentedByRespondent(caseId, msg.sender, description); emit CaseVoting(caseId); } function startVotingCase(bytes32 caseId) external hasStatus(caseId, CasesLib.CaseStatus.OPENED) laterOn(lib.getVotingDate(caseId)) { lib.setCaseStatus(caseId, CasesLib.CaseStatus.VOTING); emit CaseVoting(caseId); } function commitVote(bytes32 caseId, bytes32 voteHash) external hasStatus(caseId, CasesLib.CaseStatus.VOTING) before(lib.getRevealingDate(caseId)) { require(lib.isRefereeSetToCase(msg.sender, caseId)); //referee must be set to case require(!lib.isRefereeVoted(msg.sender, caseId)); //referee can not vote twice lib.setRefereeVoteHash(caseId, msg.sender, voteHash); emit CaseVoteCommitted(caseId, msg.sender, voteHash); if (lib.getRefereeVoteHashCount(caseId) == lib.getRefereeCountByCase(caseId)) { lib.setCaseStatus(caseId, CasesLib.CaseStatus.REVEALING); emit CaseRevealingVotes(caseId); } } function startRevealingVotes(bytes32 caseId) external hasStatus(caseId, CasesLib.CaseStatus.VOTING) laterOn(lib.getRevealingDate(caseId)) { lib.setCaseStatus(caseId, CasesLib.CaseStatus.REVEALING); emit CaseRevealingVotes(caseId); } function revealVote(bytes32 caseId, address referee, uint8 voteOption, bytes32 salt) external hasStatus(caseId, CasesLib.CaseStatus.REVEALING) before(lib.getCloseDate(caseId)) { doRevealVote(caseId, referee, voteOption, salt); checkShouldMakeVerdict(caseId); } function revealVotes(bytes32 caseId, address[] referees, uint8[] voteOptions, bytes32[] salts) external hasStatus(caseId, CasesLib.CaseStatus.REVEALING) before(lib.getCloseDate(caseId)) { require((referees.length == voteOptions.length) && (referees.length == salts.length)); for (uint i = 0; i < referees.length; i++) { doRevealVote(caseId, referees[i], voteOptions[i], salts[i]); } checkShouldMakeVerdict(caseId); } function checkShouldMakeVerdict(bytes32 caseId) private { if (lib.getRefereeVotesFor(caseId, true) + lib.getRefereeVotesFor(caseId, false) == lib.getRefereeVoteHashCount(caseId)) { makeVerdict(caseId); } } function doRevealVote(bytes32 caseId, address referee, uint8 voteOption, bytes32 salt) private { require(verifyVote(caseId, referee, voteOption, salt)); lib.setRefereeVote(caseId, referee, voteOption == 0); emit CaseVoteRevealed(caseId, referee, voteOption, salt); } function createVoteHash(uint8 voteOption, bytes32 salt) public view returns(bytes32) { return keccak256(voteOption, salt); } function verifyVote(bytes32 caseId, address referee, uint8 voteOption, bytes32 salt) public view returns(bool){ return lib.getRefereeVoteHash(caseId, referee) == keccak256(voteOption, salt); } function verdict(bytes32 caseId) external hasStatus(caseId, CasesLib.CaseStatus.REVEALING) laterOn(lib.getCloseDate(caseId)) { makeVerdict(caseId); } function makeVerdict(bytes32 caseId) private { uint forApplicant = lib.getRefereeVotesFor(caseId, true); uint forRespondent = lib.getRefereeVotesFor(caseId, false); uint refereeAward = lib.getRefereeAward(caseId); bool isNotEnoughVotes = (forApplicant + forRespondent) < lib.getRefereeCountNeed(caseId); bool isEthRefereeAward = lib.isEthRefereeAward(caseId); if (isNotEnoughVotes || (forApplicant == forRespondent)) { withdrawTo(isEthRefereeAward, lib.getApplicant(caseId), refereeAward); lib.setCaseStatus(caseId, CasesLib.CaseStatus.CANCELED); CasesLib.CaseCanceledCode causeCode = isNotEnoughVotes ? CasesLib.CaseCanceledCode.NOT_ENOUGH_VOTES : CasesLib.CaseCanceledCode.EQUAL_NUMBER_OF_VOTES; lib.setCaseCanceledCode(caseId, causeCode); emit CaseCanceled(caseId, uint8(causeCode)); withdrawAllRefereeVotes(caseId); return; } bool won = false; uint awardPerReferee; if (forApplicant > forRespondent) { won = true; awardPerReferee = refereeAward / forApplicant; } else { awardPerReferee = refereeAward / forRespondent; } lib.setCaseStatus(caseId, CasesLib.CaseStatus.CLOSED); lib.setCaseWon(caseId, won); emit CaseClosed(caseId, won); address[] memory wonReferees = lib.getRefereesFor(caseId, won); for (uint i = 0; i < wonReferees.length; i++) { withdrawTo(isEthRefereeAward, wonReferees[i], awardPerReferee); emit RefereeAwarded(wonReferees[i], caseId, awardPerReferee); } withdrawRefereeVotes(caseId); } function withdrawTo(bool isEth, address to, uint amount) private { if (isEth) { require(PaymentHolder(paymentHolder).withdrawEth(to, amount)); } else { require(PaymentHolder(paymentHolder).withdrawToken(to, amount, address(bkxToken))); } } function withdrawAllRefereeVotes(bytes32 caseId) private { address[] memory referees = lib.getRefereesByCase(caseId); for (uint i = 0; i < referees.length; i++) { withdrawRefereeVote(referees[i]); } } function withdrawRefereeVotes(bytes32 caseId) private { address[] memory referees = lib.getRefereesByCase(caseId); for (uint i = 0; i < referees.length; i++) { if (!lib.isRefereeVoted(referees[i], caseId)) { withdrawRefereeVote(referees[i]); } } } function withdrawRefereeVote(address referee) private { uint voteBalance = lib.getVotes(referee); voteBalance += 1; lib.setVotes(referee, voteBalance); emit RefereeVoteBalanceChanged(referee, voteBalance); } }
_key The key for the record
function setString(bytes32 _key, string _value) onlyLatestContract external { stringStorage[_key] = _value; }
1,795,318
./full_match/1/0x13C2A723e57A83612F3D844D81bb8b7233C5158C/sources/contracts/OCBStaking.sol
Internal unstake function
function _unstake(address recipient, uint256 tokenId) internal { Position storage stakingPosition = stakingPositions[tokenId]; if( recipient != stakingPosition.owner ) revert SenderIsNotTokenOwner(tokenId); if( stakingPosition.startTime <= 0 ) revert TokenIsNotStaked(tokenId); stakingPosition.owner = address(0); stakingPosition.startTime = 0; ocbContract.transferFrom(address(this), recipient, tokenId); emit TokenUnstaked(tokenId, recipient); }
4,857,337
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Address.sol"; import "./CollaborativeOwnable.sol"; import "./ERC721Enumerable.sol"; import "./IOwlToken.sol"; import "./MerkleProof.sol"; import "./ProxyRegistry.sol"; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./Strings.sol"; contract NightOwls is ERC721Enumerable, CollaborativeOwnable, ReentrancyGuard { using SafeMath for uint256; using Address for address; using Strings for uint256; uint256 public maxSupply = 2420; string public baseURI = ""; address public proxyRegistryAddress = address(0); address public owlTokenAddress = address(0); uint256 public mintPrice = 50000000000000000; uint16 public mintLimit = 4; bool public mintIsActive = false; mapping(address => uint16) public whitelistMinted; bytes32 public whitelistMerkleRoot; uint256 public whitelistMintPrice = 50000000000000000; uint16 public whitelistMintLimit = 2; bool public whitelistMintIsActive = false; mapping(address => bool) public prepaidMinted; bytes32 public prepaidMerkleRoot; bool public prepaidMintIsActive = false; uint16 public reservedForPrepaid = 0; address public projectWithdrawAddress = address(0); address public developerWithdrawAddress = address(0); uint16 public developerPercentage = 155; constructor(address _proxyRegistryAddress, address _developerWithdrawAddress, address _projectWithdrawAddress) ERC721("Night Owls", "OWLS") { proxyRegistryAddress = _proxyRegistryAddress; developerWithdrawAddress = _developerWithdrawAddress; projectWithdrawAddress = _projectWithdrawAddress; } // // Public / External // function remainingForMint() public view returns (uint256) { uint256 ts = totalSupply(); uint256 available = maxSupply.sub(ts.add(reservedForPrepaid)); return available; } function mint(uint16 quantity) external payable nonReentrant { require(mintIsActive); require(quantity > 0 && quantity <= mintLimit && quantity <= remainingForMint()); require(msg.value >= mintPrice.mul(quantity)); uint256 ts = totalSupply(); for (uint16 i = 0; i < quantity; i++) { _safeMint(_msgSender(), ts + i); } } function whitelistMint(bytes32[] calldata merkleProof, uint16 quantity) external payable nonReentrant { require(whitelistMintIsActive); require(quantity > 0 && quantity <= whitelistMintLimit && quantity <= remainingForMint()); require(msg.value >= whitelistMintPrice.mul(quantity)); uint16 alreadyMinted = whitelistMinted[_msgSender()]; require(alreadyMinted < whitelistMintLimit); bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(merkleProof, whitelistMerkleRoot, leaf), "1"); uint256 ts = totalSupply(); for (uint16 i = 0; i < quantity; i++) { _safeMint(_msgSender(), ts + i); } whitelistMinted[_msgSender()] = alreadyMinted + quantity; } function prepaidMint(bytes32[] calldata merkleProof, uint16 quantity) external nonReentrant { require(prepaidMintIsActive); require(quantity > 0 && quantity <= reservedForPrepaid); require(!prepaidMinted[_msgSender()]); bytes32 leaf = keccak256(abi.encodePacked(_msgSender(), uint256(quantity))); require(MerkleProof.verify(merkleProof, prepaidMerkleRoot, leaf), "2"); uint256 ts = totalSupply(); require(ts.add(quantity) <= maxSupply); for (uint16 i = 0; i < quantity; i++) { _safeMint(_msgSender(), ts + i); } prepaidMinted[_msgSender()] = true; reservedForPrepaid = reservedForPrepaid - quantity; } // Override ERC721 function _baseURI() internal view override returns (string memory) { return baseURI; } // Override ERC721 function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId)); string memory __baseURI = _baseURI(); return bytes(__baseURI).length > 0 ? string(abi.encodePacked(__baseURI, tokenId.toString(), ".json")) : '.json'; } // Override ERC721 function isApprovedForAll(address owner, address operator) override public view returns (bool) { if (address(proxyRegistryAddress) != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } // Override ERC721 function transferFrom(address from, address to, uint256 tokenId) public override { if (owlTokenAddress != address(0)) { IOwlToken(owlTokenAddress).onNightOwlTransfer(from, to); } super.transferFrom(from, to, tokenId); } // Override ERC721 function safeTransferFrom(address from, address to, uint256 tokenId) public override { if (owlTokenAddress != address(0)) { IOwlToken(owlTokenAddress).onNightOwlTransfer(from, to); } super.safeTransferFrom(from, to, tokenId); } // Override ERC721 function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override { if (owlTokenAddress != address(0)) { IOwlToken(owlTokenAddress).onNightOwlTransfer(from, to); } super.safeTransferFrom(from, to, tokenId, data); } // // Collaborator Access // function setBaseURI(string memory uri) external onlyCollaborator { baseURI = uri; } function reduceMaxSupply(uint256 newMaxSupply) external onlyCollaborator { require(newMaxSupply >= 0 && newMaxSupply < maxSupply); require(newMaxSupply >= totalSupply()); maxSupply = newMaxSupply; } function reduceMintPrice(uint256 newPrice) external onlyCollaborator { require(newPrice >= 0 && newPrice < mintPrice); mintPrice = newPrice; } function reduceWhitelistMintPrice(uint256 newPrice) external onlyCollaborator { require(newPrice >= 0 && newPrice < whitelistMintPrice); whitelistMintPrice = newPrice; } function airDrop(address to, uint16 quantity) external onlyCollaborator { require(to != address(0)); require(quantity > 0); require(quantity <= remainingForMint()); uint256 ts = totalSupply(); for (uint16 i = 0; i < quantity; i++) { _safeMint(to, ts + i); } } function setMintIsActive(bool active) external onlyCollaborator { mintIsActive = active; } function setWhitelistMintIsActive(bool active) external onlyCollaborator { whitelistMintIsActive = active; } function setWhitelistMerkleRoot(bytes32 newRoot) external onlyCollaborator { whitelistMerkleRoot = newRoot; } function setPrepaidMintIsActive(bool active) external onlyCollaborator { prepaidMintIsActive = active; } function setPrepaidMerkleRoot(bytes32 newRoot, uint16 newReserved) external onlyCollaborator { require(newReserved <= maxSupply); prepaidMerkleRoot = newRoot; reservedForPrepaid = newReserved; } function setProxyRegistryAddress(address prAddress) external onlyCollaborator { proxyRegistryAddress = prAddress; } function setOwlTokenAddress(address newAddress) external onlyCollaborator { owlTokenAddress = newAddress; } function withdraw() external onlyCollaborator nonReentrant { uint256 balance = address(this).balance; uint256 developerBalance = balance.mul(developerPercentage).div(1000); uint256 collaboratorBalance = balance.sub(developerBalance); payable(projectWithdrawAddress).transfer(collaboratorBalance); payable(developerWithdrawAddress).transfer(developerBalance); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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); // 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.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "./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.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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOwlToken { function redeemTokens(address addr, uint256 amount) external; function onNightOwlTransfer(address from, address to) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "./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.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 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 // OpenZeppelin Contracts v4.4.0 (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)); 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()); 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 // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./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)); 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)); 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)); 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); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender())); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId)); 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)); _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)); _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)); } /** * @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)); 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)); } /** * @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)); require(!_exists(tokenId)); _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); require(to != address(0)); _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); _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.0 (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.0 (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 pragma solidity ^0.8.0; import "./Ownable.sol"; import "./Address.sol"; abstract contract CollaborativeOwnable is Ownable { using Address for address; mapping(address => bool) private _collaborators; uint256 private _collaboratorCount; constructor() { } function isCollaborator(address collaboratorAddress) public view virtual returns (bool) { return _collaborators[collaboratorAddress]; } modifier onlyCollaborator() { require(owner() == _msgSender() || _collaborators[_msgSender()], "CO1"); _; } function addCollaborator(address collaboratorAddress) public onlyCollaborator { require(collaboratorAddress != address(0), "CO2"); require(!_collaborators[collaboratorAddress], "CO3"); _collaborators[collaboratorAddress] = true; _collaboratorCount++; } function removeCollaborator(address collaboratorAddress) public onlyCollaborator { require(collaboratorAddress != address(0), "CO4"); require(_collaborators[collaboratorAddress], "CO4"); require(_collaboratorCount > 1, "CO4"); _collaborators[collaboratorAddress] = false; _collaboratorCount--; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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); } } } }
See {IERC721-balanceOf}./
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0)); return _balances[owner]; }
140,387
./full_match/1/0x97b6a74BcC7Bfc03e9Ce97DE7Fb82a4a03b110Bf/sources/contracts/Pool/Pool.sol
@inheritdoc IPool Lender should have principal Lender should not have created callback Callback can be created only before the maturity date If last lender requests callback and roll is requested then roll is rejected
function requestCallBack() external override onlyPrime nonDefaulted nonClosed returns (bool success) { require(poolMembers[msg.sender].principal != 0, 'LZL'); require(!_poolCallbacks[msg.sender].isCreated, 'AAD'); require(block.timestamp < maturityDate, 'EMD'); if (isRollRequested) { _rejectRoll(); } emit CallbackCreated(msg.sender); return true; }
16,489,427
// File: openzeppelin-solidity/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.8; /** * @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-solidity/contracts/token/ERC20/IERC20.sol /** * @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-solidity/contracts/GSN/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 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-solidity/contracts/utils/Address.sol /** * @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 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; } /** * @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-solidity/contracts/token/ERC20/ERC20.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) 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 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/oracle/ILinearDividendOracle.sol /** * @title ILinearDividendOracle * @notice provides dividend information and calculation strategies for linear dividends. */ interface ILinearDividendOracle { /** * @notice calculate the total dividend accrued since last dividend checkpoint to now * @param tokenAmount amount of token being held * @param timestamp timestamp to start calculating dividend accrued * @param fromIndex index in the dividend history that the timestamp falls into * @return amount of dividend accrued in 1e18, and the latest dividend index */ function calculateAccruedDividends( uint256 tokenAmount, uint256 timestamp, uint256 fromIndex ) external view returns (uint256, uint256); /** * @notice calculate the total dividend accrued since last dividend checkpoint to (inclusive) a given dividend index * @param tokenAmount amount of token being held * @param timestamp timestamp to start calculating dividend accrued * @param fromIndex index in the dividend history that the timestamp falls into * @param toIndex index in the dividend history to stop the calculation at, inclusive * @return amount of dividend accrued in 1e18, dividend index and timestamp to use for remaining dividends */ function calculateAccruedDividendsBounded( uint256 tokenAmount, uint256 timestamp, uint256 fromIndex, uint256 toIndex ) external view returns (uint256, uint256, uint256); /** * @notice get the current dividend index * @return the latest dividend index */ function getCurrentIndex() external view returns (uint256); /** * @notice return the current dividend accrual rate, in USD per second * @return dividend in USD per second */ function getCurrentValue() external view returns (uint256); /** * @notice return the dividend accrual rate, in USD per second, of a given dividend index * @return dividend in USD per second of the corresponding dividend phase. */ function getHistoricalValue(uint256 dividendIndex) external view returns (uint256); } // File: contracts/standardTokens/WrappingERC20WithLinearDividends.sol /** * @title WrappingERC20WithLinearDividends * @dev a wrapped token from another ERC 20 token with linear dividends delegation */ contract WrappingERC20WithLinearDividends is ERC20 { using SafeMath for uint256; event Mint(address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event DividendClaimed(address indexed from, uint256 value); /** * @dev records an address's dividend state **/ struct DividendState { // amount of dividend that has been consolidated uint256 consolidatedAmount; // timestamp to start calculating newly accrued dividends from uint256 timestamp; // index of the dividend phase that the timestamp falls into uint256 index; } IERC20 public _backingToken; IERC20 public _dai; ILinearDividendOracle public _dividendOracle; // track account balances, only original holders of backing tokens can unlock their tokens mapping (address => uint256) public _lockedBalances; // track account dividend states mapping (address => DividendState) public _dividends; constructor( address backingTokenAddress, address daiAddress, address dividendOracleAddress, string memory name, string memory symbol ) public ERC20(name, symbol) { require(backingTokenAddress != address(0), "Backing token must be defined"); require(dividendOracleAddress != address(0), "Dividend oracle must be defined"); _backingToken = IERC20(backingTokenAddress); _dai = IERC20(daiAddress); _dividendOracle = ILinearDividendOracle(dividendOracleAddress); } /** * @notice deposit backing tokens to be locked, and generate wrapped tokens to sender * @param amount amount of token to wrap * @return true if successful */ function wrap(uint256 amount) external returns(bool) { return wrapTo(msg.sender, amount); } /** * @notice deposit backing tokens to be locked, and generate wrapped tokens to recipient * @param recipient address to receive wrapped tokens * @param amount amount of tokens to wrap * @return true if successful */ function wrapTo(address recipient, uint256 amount) public returns(bool) { require(recipient != address(0), "Recipient cannot be zero address"); // transfer backing token from sender to this contract to be locked _backingToken.transferFrom(msg.sender, address(this), amount); // update how many tokens the sender has locked in total _lockedBalances[msg.sender] = _lockedBalances[msg.sender].add(amount); // mint wTokens to recipient _mint(recipient, amount); emit Mint(recipient, amount); return true; } /** * @notice burn wrapped tokens to unlock backing tokens to sender * @param amount amount of token to unlock * @return true if successful */ function unwrap(uint256 amount) external returns(bool) { return unwrapTo(msg.sender, amount); } /** * @notice burn wrapped tokens to unlock backing tokens to recipient * @param recipient address to receive backing tokens * @param amount amount of tokens to unlock * @return true if successful */ function unwrapTo(address recipient, uint256 amount) public returns (bool) { require(recipient != address(0), "Recipient cannot be zero address"); // burn wTokens from sender, burn should revert if not enough balance _burn(msg.sender, amount); // update how many tokens the sender has locked in total _lockedBalances[msg.sender] = _lockedBalances[msg.sender].sub(amount, "Cannot unlock more than the locked amount"); // transfer backing token from this contract to recipient _backingToken.transfer(recipient, amount); emit Burn(msg.sender, amount); return true; } /** * @notice return locked balances of backing tokens for a given account * @param account account to query for * @return balance of backing token being locked */ function lockedBalance(address account) external view returns (uint256) { return _lockedBalances[account]; } /** * @notice withdraw all accrued dividends by the sender to the sender * @return true if successful */ function claimAllDividends() external returns (bool) { return claimAllDividendsTo(msg.sender); } /** * @notice withdraw all accrued dividends by the sender to the recipient * @param recipient address to receive dividends * @return true if successful */ function claimAllDividendsTo(address recipient) public returns (bool) { require(recipient != address(0), "Recipient cannot be zero address"); consolidateDividends(msg.sender); uint256 dividends = _dividends[msg.sender].consolidatedAmount; _dividends[msg.sender].consolidatedAmount = 0; _dai.transfer(recipient, dividends); emit DividendClaimed(msg.sender, dividends); return true; } /** * @notice withdraw portion of dividends by the sender to the sender * @return true if successful */ function claimDividends(uint256 amount) external returns (bool) { return claimDividendsTo(msg.sender, amount); } /** * @notice withdraw portion of dividends by the sender to the recipient * @param recipient address to receive dividends * @param amount amount of dividends to withdraw * @return true if successful */ function claimDividendsTo(address recipient, uint256 amount) public returns (bool) { require(recipient != address(0), "Recipient cannot be zero address"); consolidateDividends(msg.sender); uint256 dividends = _dividends[msg.sender].consolidatedAmount; require(amount <= dividends, "Insufficient dividend balance"); _dividends[msg.sender].consolidatedAmount = dividends.sub(amount); _dai.transfer(recipient, amount); emit DividendClaimed(msg.sender, amount); return true; } /** * @notice view total accrued dividends of a given account * @param account address of the account to query for * @return total accrued dividends */ function dividendsAvailable(address account) external view returns (uint256) { uint256 balance = balanceOf(account); // short circut if balance is 0 to avoid potentially looping from 0 dividend index if (balance == 0) { return _dividends[account].consolidatedAmount; } (uint256 dividends,) = _dividendOracle.calculateAccruedDividends( balance, _dividends[account].timestamp, _dividends[account].index ); return _dividends[account].consolidatedAmount.add(dividends); } /** * @notice view dividend state of an account * @param account address of the account to query for * @return consolidatedAmount, timestamp, and index */ function getDividendState(address account) external view returns (uint256, uint256, uint256) { return (_dividends[account].consolidatedAmount, _dividends[account].timestamp, _dividends[account].index); } /** * @notice calculate all dividends accrued since the last consolidation, and add to the consolidated amount * @dev anybody can consolidation dividends for any account * @param account account to perform dividend consolidation on * @return true if success */ function consolidateDividends(address account) public returns (bool) { uint256 balance = balanceOf(account); // balance is at 0, re-initialize dividend state if (balance == 0) { initializeDividendState(account); return true; } (uint256 dividends, uint256 newIndex) = _dividendOracle.calculateAccruedDividends( balance, _dividends[account].timestamp, _dividends[account].index ); _dividends[account].consolidatedAmount = _dividends[account].consolidatedAmount.add(dividends); _dividends[account].timestamp = block.timestamp; _dividends[account].index = newIndex; return true; } /** * @notice perform dividend consolidation to the given dividend index * @dev this function can be used if consolidateDividends fails due to running out of gas in an unbounded loop. * In such case, dividend consolidation can be broken into several transactions. * However, dividend rates do not change frequently, * this function should not be needed unless account stays dormant for a long time, e.g. a decade. * @param account account to perform dividend consolidation on * @param toDividendIndex dividend index to stop consolidation at, inclusive * @return true if success */ function consolidateDividendsToIndex(address account, uint256 toDividendIndex) external returns (bool) { uint256 balance = balanceOf(account); // balance is at 0, re-initialize dividend state if (balance == 0) { initializeDividendState(account); return true; } (uint256 dividends, uint256 newIndex, uint256 newTimestamp) = _dividendOracle.calculateAccruedDividendsBounded( balance, _dividends[account].timestamp, _dividends[account].index, toDividendIndex ); _dividends[account].consolidatedAmount = _dividends[account].consolidatedAmount.add(dividends); _dividends[account].timestamp = newTimestamp; _dividends[account].index = newIndex; return true; } /** * @notice setups for parameters for dividend accrual calculations * @param account account to setup for */ function initializeDividendState(address account) internal { // initialize the time to start dividend accrual _dividends[account].timestamp = block.timestamp; // initialize the dividend index to start dividend accrual _dividends[account].index = _dividendOracle.getCurrentIndex(); } /** * @notice consolidate dividends with the balance as is, the new balance will initiate dividend calculations from 0 again * @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. */ function _beforeTokenTransfer(address from, address to, uint256) internal virtual override { if (from != address(0)) { consolidateDividends(from); } if (to != address(0) && to != from) { consolidateDividends(to); } } }
deposit backing tokens to be locked, and generate wrapped tokens to recipient recipient address to receive wrapped tokens amount amount of tokens to wrap return true if successful/ transfer backing token from sender to this contract to be locked update how many tokens the sender has locked in total mint wTokens to recipient
function wrapTo(address recipient, uint256 amount) public returns(bool) { require(recipient != address(0), "Recipient cannot be zero address"); _backingToken.transferFrom(msg.sender, address(this), amount); _lockedBalances[msg.sender] = _lockedBalances[msg.sender].add(amount); _mint(recipient, amount); emit Mint(recipient, amount); return true; }
7,716,821
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "./ReservationContract.sol"; /** * @author James Spivey <[email protected]> * @title Reservation Factory * @dev * This contract creates new contracts to track reservations. * It's purpose is to simply be the manager of an X number of reservations. * It makes tracking reservations easier and by being a factory easier to read/reason. */ contract ReservationContractFactory is Pausable { using SafeMath for uint256; /* These are the events for all of the different states that this contract can be in. This will help the UI to update the list as these items occur. I dispatch here and in the reservation itself for tracability. */ event ReservationFactoryCreate( bytes32 id, address owner, address renter ); event ReservationFactoryConfirm( bytes32 id, address caller ); event ReservationFactoryActivate( bytes32 id, address caller ); event ReservationFactoryComplete( bytes32 id, address caller ); event ReservationFactoryCancel( bytes32 id, address caller ); //Holds a reservation by unique ID mapping(bytes32 => address) internal reservationsById; //Holds list of reservations by address mapping(address => address[]) internal reservationsByUserId; constructor() public {} /** @dev Ensures a reservation exists in map * @param _resId Unique generated reservation ID */ modifier validReservation( bytes32 _resId ) { require( reservationsById[_resId] != 0, "Must supply a valid rental Id" ); _; } /** @dev Creates a new unique reservation ID to be referenced * @param _renter Address of the vehicle renter * @param _owner Address of the vehicle owner * @param _createdDate Date reservation created. GUI created timestamp * @param _blockNumber Block number of transaction. Ensures uniqueness * @return Generated unique ID */ function createReservationId( address _renter, address _owner, uint256 _createdDate, uint256 _blockNumber ) private pure returns (bytes32) { //Return packed ID /* solium-disable-next-line */ return sha256(abi.encodePacked( _owner, _renter, _createdDate, _blockNumber )); } /** @dev Creates the reservation. Passed the value to the new contract. * Can not be called if contracts are paused. * @param _owner Address of the vehicle owner * @param _nights Number of nights being rented * @param _rate Agreed rate at time of booking in wei * @param _createdDate Date reservation created. GUI created timestamp * @param _startDate Date reservation begins * @param _endDate Date reservation ends * @return Generated unique ID */ function createReservation( address _owner, uint8 _nights, uint256 _rate, uint256 _totalCost, uint256 _createdDate, uint256 _startDate, uint256 _endDate ) public payable whenNotPaused returns (bytes32) { //Ensure the amount sent is enough to fill the reservation require( msg.value == _totalCost, "Value sent does not equal reservation total cost" ); //Get a unique ID for the reservation for tracking purposes. bytes32 resId = createReservationId( msg.sender, _owner, _createdDate, block.number ); //This protects against re-entrancy require( reservationsById[resId] == 0, "This reservation already exists" ); //Create new reservation and send value along ReservationContract newReso = (new ReservationContract).value(msg.value)( msg.value, msg.sender, resId, _owner, _nights, _rate, _createdDate, _startDate, _endDate ); reservationsById[resId] = newReso; //Store by ID for fastest lookup reservationsByUserId[msg.sender].push(newReso); //Map for reservations by Renter reservationsByUserId[_owner].push(newReso); //Map for reservations by Owner emit ReservationFactoryCreate(resId, _owner, msg.sender); return resId; //Send back new unique ID } /** @dev Gets a reservation by unique generated ID * @param _resId Unique generated reservation ID * @return Reservation address */ function getReservationById(bytes32 _resId) public view returns (address) { return reservationsById[_resId]; } /** @dev Gets a reservation by a users address * @param _userId Users address * @return Array of reservation addresses */ function getReservationsByUserId(address _userId) public view returns (address[]) { return reservationsByUserId[_userId]; } /** @dev Accepts a reservation, validates is a valid reservation. * Reservation contract validates everything else. * @param _resId Unique generated reservation ID */ function accept(bytes32 _resId) public validReservation(_resId) { ReservationContract(reservationsById[_resId]).accept(msg.sender); emit ReservationFactoryConfirm(_resId, msg.sender); } /** @dev Starts a reservation, validates is a valid reservation/ * Reservation contract validates everything else. * @param _resId Unique generated reservation ID */ function start(bytes32 _resId) public validReservation(_resId) { ReservationContract(reservationsById[_resId]).start(msg.sender); emit ReservationFactoryActivate(_resId, msg.sender); } /** @dev Completes a reservation, validates is a valid reservation. * Reservation contract validates everything else. * @param _resId Unique generated reservation ID */ function complete(bytes32 _resId) public validReservation(_resId) { ReservationContract(reservationsById[_resId]).complete(msg.sender); emit ReservationFactoryComplete(_resId, msg.sender); } /** @dev Cancels a reservation, validates is a valid reservation. * Reservation contract validates everything else. * @param _resId Unique generated reservation ID */ function cancel(bytes32 _resId) public validReservation(_resId) { ReservationContract(reservationsById[_resId]).cancel(msg.sender); emit ReservationFactoryCancel(_resId, msg.sender); } /** @dev Dont receive ether via fallback. */ function () public { } }
Starts a reservation, validates is a valid reservation/ Reservation contract validates everything else. _resId Unique generated reservation ID/
function start(bytes32 _resId) public validReservation(_resId) { ReservationContract(reservationsById[_resId]).start(msg.sender); emit ReservationFactoryActivate(_resId, msg.sender); }
895,438
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.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 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 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // File: @openzeppelin/contracts/access/Ownable.sol // 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); } } // File: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // 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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // 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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (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); /** * @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/extensions/IERC721Metadata.sol // 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); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (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; // 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); _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"); _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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // 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(); } } // File: contracts/TheLandMark.sol /** .:+shhdhhyo/-` `-/oyhhdhhs+:. ./sdNMMMMMMMMMNmh+- -+hmNMMMMMMMMMNds/. :smMMMMMMMMMMMMMMMNho-. .-odNMMMMMMMMMMMMMMMms: /hMMMMMMMMMMNmmmmmmNMMmhs+::--::+shmMMNmmmmmmNMMMMMMMMMMh/ :yMMMMMMMMNdhdmNNNmmdhdNMMNNNNNNNNMMNdhdmmNNNmdhdNMMMMMMMMy: omMMMMMMNhhNMMMMMMMMMMmhdmNMMMMMMNmdhmMMMMMMMMMMNhhNMMMMMMmo sNMMMMMNydMMMMMMMMNNNNNMNddddddddddNMNNNNNMMMMMMMMdyNMMMMMNs omMMMMMhhMMMMMMNmdmmNmmdmNMMNNNNMMNmdmmNmmdmNMMMMMMhhMMMMMmo :yMMMMMymMMMMMmdNMMMMMMMNddmNNNNmddNMMMMMMMNdmMMMMMmyMMMMMy: /hMMMMymMMMMmhMMMMMMMMMMMMNmmmmNMMMMMMMMMMMMhmMMMMdyMMMMh/ :ymMMmyNMMMdmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMmdMMMNymMMmy: .+hNMmymMMmdMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMhmMMmymMNh/. :yNMNhhNMddNMMMMMMMMMMMMMMMMMMMMMMMMMMNddMNhhNMNy: /hMMMdyMMmhNMMMMMMMMMMMMMMMMMMMMMMMMNhmMMydMMMh/ /yMMNhhMMhdMMMMMMMMMMMMMMMMMMMMMMMMMMMMdhMMhhNMMy/ -+hMMdyNMMmdMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMdmMMmydMMh+- /yNMMmyNMMMdmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMmdMMMNymMMNy/ +dMMMMymMMMMNhMMMMMMMMMMMNmmmmmmNMMMMMMMMMMMhNMMMMmyMMMMh+ :hMMMMMymMMMMMmdmMMMMMMMNddNNNNNNddNMMMMMMMmdmMMMMMmyMMMMMy: omMMMMMdhMMMMMMNmddmmmddmNMNNNNNNMNmddmmmddmNMMMMMMhdMMMMMmo sNMMMMMMydMMMMMMMMMNNNMMmdhddmmddhdmMMNNNMMMMMMMMMdyMMMMMMNo omMMMMMMMdhmNMMMMMMMMNmhdNMMMMMMMMNdhmNMMMMMMMMNmhdMMMMMMMmo -yNMMMMMMMNdhddmmmmdhhmNMMNNmmmmNNMMNmhhdmmmmddhdNMMMMMMMNy- /yNMMMMMMMMMMNmmmmNMMNdyo/:-..-:/oydNMMNmmmmNMMMMMMMMMMNy/ -odMMMMMMMMMMMMMMMNh+-` `-+hNMMMMMMMMMMMMMMMdo- -ohmMMMMMMMMMNdy/. ./ydNMMMMMMMMNmho- .-/oyhhhys+:.` `.:+syhhhyo/-. */ pragma solidity >=0.7.0 <0.9.0; interface LandToken { function balanceOf(address owner) external view returns (uint256 balance); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract Thelandmark is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; string public baseExtension = ".json"; uint256 public gif = 20; //Gift uint256 public gifIDs = 1000000000000; //Gif ID uint256 public _maxperWalletWhiteList = 6; // Whitlist max mint per wallet uint256 public _maxperWalletMintPass = 50; // MintPass max Mint per wallet uint256 public _maxperWalletMint = 50; // Mint max Mint per wallet uint256 public _maxperTX = 50; // Max per mint uint256 public _limit = 10000; // Supply of token uint256 public _reserved = 500; // Reserved for team and marketing uint256 public _price = 0.15 ether; // Price uint256 public whitelist_count = 0; // Start count for whitelist uint256 public mintpass_count = 0; // Start count for mintpass uint256 public mint_count = 0; // Start count for mint bool public _presalePassPaused = true; // Contract is paused bool public _presaleWLPaused = true; // Contract is paused bool public _PublicPaused = true; // Contract is paused mapping (address => uint256) public perWallet; // Mapping per wallet mapping (address => bool) public mintpass; // Mapping per minpass mapping (address => bool) public whitelist; // Mapping per whitelist LandToken public TokenContract; // Token functions address payable public payments; // Paybale bool public isBurningActive = false; // Paused for Burning Function // Constructor for the token constructor(string memory initbaseURI, address _payments) ERC721("The Landmark", "TLM") { require(_payments != address(0), "Zero address error"); setBaseURI(initbaseURI); payments = payable(_payments); } // Receive function in case someone wants to donate some ETH to the contract receive() external payable {} // Internal URI function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } // Token Public only owner fuctions function setLandToken (LandToken _TokenContract) public onlyOwner{ // require(_TokenContract != address(0), "Contract address can't be zero address"); TokenContract = _TokenContract; } // Public view token function getLandToken(address __address) public view returns(uint256) { require(__address != address(0), "Contract address can't be zero address"); return TokenContract.balanceOf(__address); } // Get Allowance public view function getLandAllowance(address __address) public view returns(uint256) { require(__address != address(0), "Contract address can't be zero address"); return TokenContract.allowance(__address, address(this)); } // Mint Function public payble function MINT(uint256 num) public payable { uint256 supply = totalSupply(); require( !_PublicPaused, "Sale paused" ); require( num <= _maxperTX, "You are exceeding limit of per transaction TLM" ); require( perWallet[msg.sender] + num <= _maxperWalletMint, "You are exceeding limit of per wallet TLM" ); require( num > 0); require( supply + num <= _limit - _reserved, "Exceeds maximum TLM supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i = 1 ; i <= num; i++){ _safeMint( msg.sender, supply + i ); } perWallet[msg.sender] += num; } // Giveaway Function external only owner to provide the token for the winners function giveAway(address _to, uint256 _amount) external onlyOwner() { require( _to != address(0), "Zero address error"); require( _amount <= _reserved, "Exceeds reserved Landmark supply"); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } // Function mint for gif by the owner to spesfic address function mint_g(address _to, uint256 _amount) external onlyOwner() { require( _to != address(0), "Zero address error"); require( _amount <= gif, "Exceeds gif supply" ); for(uint256 i; i < _amount; i++){ _safeMint( _to, gifIDs ); gif --; gifIDs++; } } // Internal memory with bublic view for the wallet of owner function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // MINTPASS Mint public payable only for the Mintpass Holders function MINTPASS_MINT(uint256 num) public payable { uint256 supply = totalSupply(); require( !_presalePassPaused, "Sale paused" ); require( mintpass[msg.sender] == true, "Only MINTPASS can mint" ); require( perWallet[msg.sender] + num <= _maxperWalletMintPass, "You are exceeding limit of per wallet TLM" ); require( supply + num <= _limit - _reserved, "Exceeds maximum TLM supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i; i < num; i++){ _safeMint( msg.sender, supply + i ); } perWallet[msg.sender] += num; } // Bulk MintPass wallets function bulk_mintpass(address[] memory addresses) public onlyOwner() { for(uint i=0; i < addresses.length; i++){ address addr = addresses[i]; if(mintpass[addr] != true && addr != address(0)){ mintpass[addr] = true; mintpass_count++; } } } // Function remove MitPass wallet / only owner function remove_mintpass(address _address) public onlyOwner() { require(_address != address(0), "Zero address error"); mintpass[_address] = false; mintpass_count--; } // Whitlist Mint public payable only for the whitlisted people function WHITELIST_MINT(uint256 num) public payable { uint256 supply = totalSupply(); require( !_presaleWLPaused, "Sale paused" ); require( whitelist[msg.sender] == true, "Only WHITELIST can mint" ); require( perWallet[msg.sender] + num <= _maxperWalletWhiteList, "You are exceeding limit of per wallet TLM" ); require( supply + num <= _limit - _reserved, "Exceeds maximum TLM supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i; i < num; i++){ _safeMint( msg.sender, supply + i ); } perWallet[msg.sender] += num; } // Bulk Whitlist wallets function bulk_whitelist(address[] memory addresses) public onlyOwner() { for(uint i=0; i < addresses.length; i++){ address addr = addresses[i]; if(whitelist[addr] != true && addr != address(0)){ whitelist[addr] = true; whitelist_count++; } } } // Function remove whiltlist wallet / only owner function remove_whitelist(address _address) public onlyOwner() { require(_address != address(0), "Zero address error"); whitelist[_address] = false; whitelist_count--; } // Just in case Eth does some crazy stuff ( Change price ) only owner function setPrice(uint256 _newPrice) public onlyOwner() { _price = _newPrice; } // Setting limits function setLimit(uint256 limit) public onlyOwner { _limit = limit; } // Max per wallet function setMaxPerWallet(uint256 limit) public onlyOwner { _maxperTX = limit; } // token URI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseTokenURI = _baseURI(); return bytes(currentBaseTokenURI).length > 0 ? string(abi.encodePacked(currentBaseTokenURI, tokenId.toString(), baseExtension)) : ""; } // Burn Function function burnForMint(uint256 _tokenId) public { require(isBurningActive, "Burning not active"); require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // Pause Burn function toggleBurningActive() public onlyOwner { isBurningActive = !isBurningActive; } // Price show public function getPrice() public view returns (uint256){ return _price; } // Public set URI if needed function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } // Pause contract public only owner function presalePassPaused() public onlyOwner { _presalePassPaused = !_presalePassPaused; } function presaleWLPaused() public onlyOwner { _presaleWLPaused = !_presaleWLPaused; } function PublicPaused() public onlyOwner { _PublicPaused = !_PublicPaused; } // Withrow fund function withdrawAll() public payable onlyOwner { (bool success, ) = payable(payments).call{value: address(this).balance}(""); require(success); } }
Function remove MitPass wallet / only owner
function remove_mintpass(address _address) public onlyOwner() { require(_address != address(0), "Zero address error"); mintpass[_address] = false; mintpass_count--; }
13,671,776
pragma solidity =0.6.6; interface IAtariswapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IAtariswapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IAtariswapRouter{ function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); 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 (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } contract AtariswapRouter is IAtariswapRouter { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'AtariswapRouter: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IAtariswapFactory(factory).getPair(tokenA, tokenB) == address(0)) { IAtariswapFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = AtariswapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = AtariswapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'AtariswapRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = AtariswapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'AtariswapRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = AtariswapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IAtariswapPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = AtariswapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IAtariswapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = AtariswapLibrary.pairFor(factory, tokenA, tokenB); IAtariswapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IAtariswapPair(pair).burn(to); (address token0,) = AtariswapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'AtariswapRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'AtariswapRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = AtariswapLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IAtariswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = AtariswapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IAtariswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = AtariswapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IAtariswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(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,) = AtariswapLibrary.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 ? AtariswapLibrary.pairFor(factory, output, path[i + 2]) : _to; IAtariswapPair(AtariswapLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = AtariswapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'AtariswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, AtariswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = AtariswapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'AtariswapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, AtariswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'AtariswapRouter: INVALID_PATH'); amounts = AtariswapLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'AtariswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(AtariswapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'AtariswapRouter: INVALID_PATH'); amounts = AtariswapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'AtariswapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, AtariswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'AtariswapRouter: INVALID_PATH'); amounts = AtariswapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'AtariswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, AtariswapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'AtariswapRouter: INVALID_PATH'); amounts = AtariswapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'AtariswapRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(AtariswapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(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,) = AtariswapLibrary.sortTokens(input, output); IAtariswapPair pair = IAtariswapPair(AtariswapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = AtariswapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? AtariswapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, AtariswapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'AtariswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'AtariswapRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(AtariswapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'AtariswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'AtariswapRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, AtariswapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'AtariswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return AtariswapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return AtariswapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return AtariswapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return AtariswapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return AtariswapLibrary.getAmountsIn(factory, amountOut, path); } } library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library AtariswapLibrary { using SafeMath for uint; // 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, 'AtariswapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'AtariswapLibrary: 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); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'a454ff5c122408c097e88c4dcb3163398d61c388fa7f3bb07817ca631333350b' // 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,) = IAtariswapPair(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, 'AtariswapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'AtariswapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(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, 'AtariswapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'AtariswapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(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, 'AtariswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'AtariswapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(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, 'AtariswapLibrary: 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, 'AtariswapLibrary: 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); } } } library TransferHelper { function safeApprove(address token, address to, uint 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: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint 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: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
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, 'AtariswapLibrary: 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); } }
11,977,437
// Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // 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 <https://www.gnu.org/licenses/>. pragma solidity 0.6.6; pragma experimental ABIEncoderV2; interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); 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 balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); } /** * @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 { function safeTransfer( ERC20 token, address to, uint256 value, string memory location ) internal { callOptionalReturn( token, abi.encodeWithSelector( token.transfer.selector, to, value ), "transfer", location ); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value, string memory location ) internal { callOptionalReturn( token, abi.encodeWithSelector( token.transferFrom.selector, from, to, value ), "transferFrom", location ); } function safeApprove( ERC20 token, address spender, uint256 value, string memory location ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: wrong approve call" ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, value ), "approve", location ); } /** * @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). * @param location Location of the call (for debug). */ function callOptionalReturn( ERC20 token, bytes memory data, string memory functionName, string memory location ) 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 implement two-steps call as callee is a contract is a responsibility of a caller. // 1. The call itself is made, and success asserted // 2. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require( success, string( abi.encodePacked( "SafeERC20: ", functionName, " failed in ", location ) ) ); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: false returned"); } } } struct Action { ActionType actionType; bytes32 protocolName; uint256 adapterIndex; address[] tokens; uint256[] amounts; AmountType[] amountTypes; bytes data; } enum ActionType { None, Deposit, Withdraw } enum AmountType { None, Relative, Absolute } /** * @title Protocol adapter interface. * @dev adapterType(), tokenType(), and getBalance() functions MUST be implemented. * @author Igor Sobolev <[email protected]> */ abstract contract ProtocolAdapter { /** * @dev MUST return "Asset" or "Debt". * SHOULD be implemented by the public constant state variable. */ function adapterType() external pure virtual returns (bytes32); /** * @dev MUST return token type (default is "ERC20"). * SHOULD be implemented by the public constant state variable. */ function tokenType() external pure virtual returns (bytes32); /** * @dev MUST return amount of the given token locked on the protocol by the given account. */ function getBalance(address token, address account) public view virtual returns (uint256); } /** * @title Adapter for OneSplit exchange. * @dev Implementation of ProtocolAdapter interface. * @author Igor Sobolev <[email protected]> */ contract OneSplitAdapter is ProtocolAdapter { bytes32 public constant override adapterType = "Exchange"; bytes32 public constant override tokenType = ""; /** * @return Amount of Uniswap pool tokens held by the given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address, address) public view override returns (uint256) { revert("OSA: no balance!"); } } /** * @title Base contract for interactive protocol adapters. * @dev deposit() and withdraw() functions MUST be implemented * as well as all the functions from ProtocolAdapter interface. * @author Igor Sobolev <[email protected]> */ abstract contract InteractiveAdapter is ProtocolAdapter { uint256 internal constant RELATIVE_AMOUNT_BASE = 1e18; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev The function must deposit assets to the protocol. * @return MUST return assets to be sent back to the `msg.sender`. */ function deposit( address[] memory tokens, uint256[] memory amounts, AmountType[] memory amountTypes, bytes memory data ) public payable virtual returns (address[] memory); /** * @dev The function must withdraw assets from the protocol. * @return MUST return assets to be sent back to the `msg.sender`. */ function withdraw( address[] memory tokens, uint256[] memory amounts, AmountType[] memory amountTypes, bytes memory data ) public payable virtual returns (address[] memory); function getAbsoluteAmountDeposit( address token, uint256 amount, AmountType amountType ) internal view virtual returns (uint256) { if (amountType == AmountType.Relative) { require(amount <= RELATIVE_AMOUNT_BASE, "L: wrong relative value!"); uint256 totalAmount; if (token == ETH) { totalAmount = address(this).balance; } else { totalAmount = ERC20(token).balanceOf(address(this)); } if (amount == RELATIVE_AMOUNT_BASE) { return totalAmount; } else { return totalAmount * amount / RELATIVE_AMOUNT_BASE; // TODO overflow check } } else { return amount; } } function getAbsoluteAmountWithdraw( address token, uint256 amount, AmountType amountType ) internal view virtual returns (uint256) { if (amountType == AmountType.Relative) { require(amount <= RELATIVE_AMOUNT_BASE, "L: wrong relative value!"); if (amount == RELATIVE_AMOUNT_BASE) { return getBalance(token, address(this)); } else { return getBalance(token, address(this)) * amount / RELATIVE_AMOUNT_BASE; // TODO overflow check } } else { return amount; } } } /** * @dev OneSplit contract interface. * Only the functions required for OneSplitInteractiveAdapter contract are added. * The OneSplit contract is available here * github.com/CryptoManiacsZone/1split/blob/master/contracts/OneSplit.sol. */ interface OneSplit { function swap( address, address, uint256, uint256, uint256[] calldata, uint256 ) external payable; function getExpectedReturn( address, address, uint256, uint256, uint256 ) external view returns (uint256, uint256[] memory); } /** * @title Interactive adapter for OneSplit exchange. * @dev Implementation of InteractiveAdapter abstract contract. * @author Igor Sobolev <[email protected]> */ contract OneSplitInteractiveAdapter is InteractiveAdapter, OneSplitAdapter { using SafeERC20 for ERC20; address internal constant ONE_SPLIT = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; /** * @notice Exchanges tokens using OneSplit contract. * @param tokens Array with one element - `fromToken` address. * @param amounts Array with one element - token amount to be exchanged. * @param amountTypes Array with one element - amount type. * @param data Bytes array with ABI-encoded `toToken` address. * @return Asset sent back to the msg.sender. * @dev Implementation of InteractiveAdapter function. */ function deposit( address[] memory tokens, uint256[] memory amounts, AmountType[] memory amountTypes, bytes memory data ) public payable override returns (address[] memory) { require(tokens.length == 1, "OSIA: should be 1 token/amount/type!"); uint256 amount = getAbsoluteAmountDeposit(tokens[0], amounts[0], amountTypes[0]); address fromToken = tokens[0]; if (fromToken == ETH) { fromToken = address(0); } else { ERC20(fromToken).safeApprove(ONE_SPLIT, amount, "OSIA!"); } address[] memory tokensToBeWithdrawn; address toToken = abi.decode(data, (address)); if (toToken == ETH) { tokensToBeWithdrawn = new address[](0); toToken = address(0); } else { tokensToBeWithdrawn = new address[](1); tokensToBeWithdrawn[0] = toToken; } swap(fromToken, toToken, amount); return tokensToBeWithdrawn; } /** * @notice This function is unavailable in Exchange type adapters. * @dev Implementation of InteractiveAdapter function. */ function withdraw( address[] memory, uint256[] memory, AmountType[] memory, bytes memory ) public payable override returns (address[] memory) { revert("OSIA: no withdraw!"); } function swap(address fromToken, address toToken, uint256 amount) internal { uint256[] memory distribution; try OneSplit(ONE_SPLIT).getExpectedReturn( fromToken, toToken, amount, uint256(1), uint256(0x040df0) // 0x040dfc to enable curve; 0x04fdf0 to enable base exchanges; ) returns (uint256, uint256[] memory result) { distribution = result; } catch Error(string memory reason) { revert(reason); } catch (bytes memory) { revert("OSIA: 1split fail![1]"); } uint256 value = fromToken == address(0) ? amount : 0; try OneSplit(ONE_SPLIT).swap.value(value)( fromToken, toToken, amount, uint256(1), distribution, uint256(0x040df0) // 0x040dfc to enable curve; 0x04fdf0 to enable base exchanges; ) {} catch Error(string memory reason) { revert(reason); } catch (bytes memory) { revert("OSIA: 1split fail![2]"); } } }
return Amount of Uniswap pool tokens held by the given account. Implementation of ProtocolAdapter interface function./
function getBalance(address, address) public view override returns (uint256) { revert("OSA: no balance!"); }
186,597
./partial_match/1/0x39EFdC3dbB57B2388CcC4bb40aC4CB1226Bc9E44/sources/lib/prb-math/src/casting/Uint128.sol
Casts a uint128 number to UD60x18. There is no overflow check because the domain of uint128 is a subset of UD60x18.
function intoUD60x18(uint128 x) internal pure returns (UD60x18 result) { result = UD60x18.wrap(uint256(x)); }
2,719,661
// SPDX-License-Identifier: MIXED // File contracts/interfaces/IOracle.sol // License-Identifier: MIT pragma solidity 0.6.12; interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File @sushiswap/core/contracts/uniswapv2/interfaces/[email protected] // License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // File @sushiswap/core/contracts/uniswapv2/interfaces/[email protected] // License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File contracts/libraries/FullMath.sol // License-Identifier: CC-BY-4.0 pragma solidity 0.6.12; // solhint-disable // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, "FullMath::mulDiv: overflow"); return fullDiv(l, h, d); } } // File contracts/libraries/FixedPoint.sol // License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // solhint-disable // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint256, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, "FixedPoint::mul: overflow"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // lossy if either numerator or denominator is greater than 112 bits function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint::fraction: div by 0"); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } } } // File contracts/oracles/wOHMTWAPOracle.sol // License-Identifier: AGPL-3.0-only // Using the same Copyleft License as in the original Repository pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable not-rely-on-time // adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol interface IAggregator { function latestAnswer() external view returns (int256 answer); } interface IWOHM { function sOHMTowOHM( uint256 _amount ) external view returns ( uint256 ); } contract wOHMTWAPOracleV1 is IOracle { using FixedPoint for *; using BoringMath for uint256; uint256 public constant PERIOD = 10 minutes; IAggregator public constant DAI_USD = IAggregator(0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9); IUniswapV2Pair public constant pair = IUniswapV2Pair(0x34d7d7Aaf50AD4944B70B320aCB24C95fa2def7c); IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65); struct PairInfo { uint256 priceCumulativeLast; uint32 blockTimestampLast; uint144 priceAverage; } PairInfo public pairInfo; function _get(uint32 blockTimestamp) public view returns (uint256) { uint256 priceCumulative = pair.price0CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); priceCumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * (blockTimestamp - blockTimestampLast); // overflows ok // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed return priceCumulative; } // Get the latest exchange rate, if no valid (recent) rate is available, return false /// @inheritdoc IOracle function get(bytes calldata data) external override returns (bool, uint256) { uint32 blockTimestamp = uint32(block.timestamp); if (pairInfo.blockTimestampLast == 0) { pairInfo.blockTimestampLast = blockTimestamp; pairInfo.priceCumulativeLast = _get(blockTimestamp); return (false, 0); } uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired if (timeElapsed < PERIOD) { return (true, pairInfo.priceAverage); } uint256 priceCumulative = _get(blockTimestamp); pairInfo.priceAverage = uint144(1e44 / WOHM.sOHMTowOHM(uint256(FixedPoint .uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed)) .mul(1e18) .decode144())).mul(uint256(DAI_USD.latestAnswer()))); pairInfo.blockTimestampLast = blockTimestamp; pairInfo.priceCumulativeLast = priceCumulative; return (true, pairInfo.priceAverage); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata data) public view override returns (bool, uint256) { uint32 blockTimestamp = uint32(block.timestamp); if (pairInfo.blockTimestampLast == 0) { return (false, 0); } uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired if (timeElapsed < PERIOD) { return (true, pairInfo.priceAverage); } uint256 priceCumulative = _get(blockTimestamp); uint144 priceAverage = uint144(1e44 / WOHM.sOHMTowOHM(uint256(FixedPoint .uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed)) .mul(1e18) .decode144())).mul(uint256(DAI_USD.latestAnswer()))); return (true, priceAverage); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); rate = 1e44 / WOHM.sOHMTowOHM(reserve1.mul(1e18) / reserve0).mul(uint256(DAI_USD.latestAnswer())); } /// @inheritdoc IOracle function name(bytes calldata) public view override returns (string memory) { return "SSpell TWAP CHAINLINK"; } /// @inheritdoc IOracle function symbol(bytes calldata) public view override returns (string memory) { return "SSpell"; } }
Check the current spot exchange rate without any state changes @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); rate = 1e44 / WOHM.sOHMTowOHM(reserve1.mul(1e18) / reserve0).mul(uint256(DAI_USD.latestAnswer())); }
2,182,456
// SPDX-License-Identifier: GPL-3.0 // Original source: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples // Modified to unpin solidity version and to support multiple pairs pragma solidity ^0.6.6; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/lib/contracts/libraries/FixedPoint.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol'; import './UniswapV2Library.sol'; import './IUniswapOracle.sol'; contract UniswapOracle is IUniswapOracle { using FixedPoint for *; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; FixedPoint.uq112x112 price0Average; FixedPoint.uq112x112 price1Average; } uint public override constant PERIOD = 24 hours; address public override immutable factory; // mapping from pair address to a list of price observations of that pair mapping(address => Observation) private pairObservations; constructor( address _factory ) public { factory = _factory; } /** * @notice Updates and stores the exchange rate * @dev For the first 24 hours the rate will be 0. */ function update( address _tokenIn, address _tokenOut ) public override { address pair = UniswapV2Library.pairFor(factory, _tokenIn, _tokenOut); Observation storage observation = pairObservations[pair]; (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = uint32(blockTimestamp - observation.timestamp); // overflow is desired // ensure that at least one full period has passed since the last update if(timeElapsed >= PERIOD) { if(observation.price0Cumulative > 0) { // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed observation.price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - observation.price0Cumulative) / timeElapsed)); observation.price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - observation.price1Cumulative) / timeElapsed)); } observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; observation.timestamp = blockTimestamp; } } /** * @notice Returns the rate after `update` has been called. */ function consult( address _tokenIn, uint _amountIn, address _tokenOut ) public override view returns (uint _amountOut) { address pair = UniswapV2Library.pairFor(factory, _tokenIn, _tokenOut); Observation storage observation = pairObservations[pair]; (address token0,) = UniswapV2Library.sortTokens(_tokenIn, _tokenOut); if (_tokenIn == token0) { _amountOut = observation.price0Average.mul(_amountIn).decode144(); } else { _amountOut = observation.price1Average.mul(_amountIn).decode144(); } } /** * @notice Calls `update` and returns the rate in a single call */ function updateAndConsult( address _tokenIn, uint _amountIn, address _tokenOut ) public override returns (uint _amountOut) { update(_tokenIn, _tokenOut); return consult(_tokenIn, _amountIn, _tokenOut); } }
Calls `update` and returns the rate in a single call/
function updateAndConsult( address _tokenIn, uint _amountIn, address _tokenOut ) public override returns (uint _amountOut) { update(_tokenIn, _tokenOut); return consult(_tokenIn, _amountIn, _tokenOut); }
5,367,011
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; //---------------------------------------------------------------------------------- // I n s t a n t // // .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo. // .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo. // .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO: // .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO' // 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO' // //---------------------------------------------------------------------------------- // // Chef Gonpachi's Crowdsale // // A fixed price token swap contract. // // Inspired by the Open Zeppelin crowsdale and delta.financial // https://github.com/OpenZeppelin/openzeppelin-contracts // // 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 // // 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. // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // Made for Sushi.com // // Enjoy. (c) Chef Gonpachi, Kusatoshi, SSMikazu 2021 // <https://github.com/chefgonpachi/MISO/> // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0 // --------------------------------------------------------------------- import "../OpenZeppelin/utils/ReentrancyGuard.sol"; import "../Access/MISOAccessControls.sol"; import "../Utils/SafeTransfer.sol"; import "../Utils/BoringBatchable.sol"; import "../Utils/BoringERC20.sol"; import "../Utils/BoringMath.sol"; import "../Utils/Documents.sol"; import "../interfaces/IPointList.sol"; import "../interfaces/IMisoMarket.sol"; contract Crowdsale is IMisoMarket, MISOAccessControls, BoringBatchable, SafeTransfer, Documents , ReentrancyGuard { using BoringMath for uint256; using BoringMath128 for uint128; using BoringMath64 for uint64; using BoringERC20 for IERC20; /// @notice MISOMarket template id for the factory contract. /// @dev For different marketplace types, this must be incremented. uint256 public constant override marketTemplate = 1; /// @notice The placeholder ETH address. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice The decimals of the auction token. uint256 private constant AUCTION_TOKEN_DECIMAL_PLACES = 18; uint256 private constant AUCTION_TOKEN_DECIMALS = 10 ** AUCTION_TOKEN_DECIMAL_PLACES; /** * @notice rate - How many token units a buyer gets per token or wei. * The rate is the conversion between wei and the smallest and indivisible token unit. * So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK * 1 wei will give you 1 unit, or 0.001 TOK. */ /// @notice goal - Minimum amount of funds to be raised in weis or tokens. struct MarketPrice { uint128 rate; uint128 goal; } MarketPrice public marketPrice; /// @notice Starting time of crowdsale. /// @notice Ending time of crowdsale. /// @notice Total number of tokens to sell. struct MarketInfo { uint64 startTime; uint64 endTime; uint128 totalTokens; } MarketInfo public marketInfo; /// @notice Amount of wei raised. /// @notice Whether crowdsale has been initialized or not. /// @notice Whether crowdsale has been finalized or not. struct MarketStatus { uint128 commitmentsTotal; bool finalized; bool usePointList; } MarketStatus public marketStatus; /// @notice The token being sold. address public auctionToken; /// @notice Address where funds are collected. address payable public wallet; /// @notice The currency the crowdsale accepts for payment. Can be ETH or token address. address public paymentCurrency; /// @notice Address that manages auction approvals. address public pointList; /// @notice The commited amount of accounts. mapping(address => uint256) public commitments; /// @notice Amount of tokens to claim per address. mapping(address => uint256) public claimed; /// @notice Event for updating auction times. Needs to be before auction starts. event AuctionTimeUpdated(uint256 startTime, uint256 endTime); /// @notice Event for updating auction prices. Needs to be before auction starts. event AuctionPriceUpdated(uint256 rate, uint256 goal); /// @notice Event for updating auction wallet. Needs to be before auction starts. event AuctionWalletUpdated(address wallet); /// @notice Event for adding a commitment. event AddedCommitment(address addr, uint256 commitment); /// @notice Event for finalization of the crowdsale event AuctionFinalized(); /// @notice Event for cancellation of the auction. event AuctionCancelled(); /** * @notice Initializes main contract variables and transfers funds for the sale. * @dev Init function. * @param _funder The address that funds the token for crowdsale. * @param _token Address of the token being sold. * @param _paymentCurrency The currency the crowdsale accepts for payment. Can be ETH or token address. * @param _totalTokens The total number of tokens to sell in crowdsale. * @param _startTime Crowdsale start time. * @param _endTime Crowdsale end time. * @param _rate Number of token units a buyer gets per wei or token. * @param _goal Minimum amount of funds to be raised in weis or tokens. * @param _admin Address that can finalize auction. * @param _pointList Address that will manage auction approvals. * @param _wallet Address where collected funds will be forwarded to. */ function initCrowdsale( address _funder, address _token, address _paymentCurrency, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, address _admin, address _pointList, address payable _wallet ) public { require(_endTime < 10000000000, "Crowdsale: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "Crowdsale: start time is before current time"); require(_endTime > _startTime, "Crowdsale: start time is not before end time"); require(_rate > 0, "Crowdsale: rate is 0"); require(_wallet != address(0), "Crowdsale: wallet is the zero address"); require(_admin != address(0), "Crowdsale: admin is the zero address"); require(_totalTokens > 0, "Crowdsale: total tokens is 0"); require(_goal > 0, "Crowdsale: goal is 0"); require(IERC20(_token).decimals() == AUCTION_TOKEN_DECIMAL_PLACES, "Crowdsale: Token does not have 18 decimals"); if (_paymentCurrency != ETH_ADDRESS) { require(IERC20(_paymentCurrency).decimals() > 0, "Crowdsale: Payment currency is not ERC20"); } marketPrice.rate = BoringMath.to128(_rate); marketPrice.goal = BoringMath.to128(_goal); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); marketInfo.totalTokens = BoringMath.to128(_totalTokens); auctionToken = _token; paymentCurrency = _paymentCurrency; wallet = _wallet; initAccessControls(_admin); _setList(_pointList); require(_getTokenAmount(_goal) <= _totalTokens, "Crowdsale: goal should be equal to or lower than total tokens"); _safeTransferFrom(_token, _funder, _totalTokens); } ///-------------------------------------------------------- /// Commit to buying tokens! ///-------------------------------------------------------- receive() external payable { revertBecauseUserDidNotProvideAgreement(); } /** * @dev Attribution to the awesome delta.financial contracts */ function marketParticipationAgreement() public pure returns (string memory) { return "I understand that I am interacting with a smart contract. I understand that tokens commited are subject to the token issuer and local laws where applicable. I reviewed code of the smart contract and understand it fully. I agree to not hold developers or other people associated with the project liable for any losses or misunderstandings"; } /** * @dev Not using modifiers is a purposeful choice for code readability. */ function revertBecauseUserDidNotProvideAgreement() internal pure { revert("No agreement provided, please review the smart contract before interacting with it"); } /** * @notice Checks the amount of ETH to commit and adds the commitment. Refunds the buyer if commit is too high. * @dev low level token purchase with ETH ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it should not be called by * another `nonReentrant` function. * @param _beneficiary Recipient of the token purchase. */ function commitEth( address payable _beneficiary, bool readAndAgreedToMarketParticipationAgreement ) public payable nonReentrant { require(paymentCurrency == ETH_ADDRESS, "Crowdsale: Payment currency is not ETH"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } /// @dev Get ETH able to be committed. uint256 ethToTransfer = calculateCommitment(msg.value); /// @dev Accept ETH Payments. uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { _addCommitment(_beneficiary, ethToTransfer); } /// @dev Return any ETH to be refunded. if (ethToRefund > 0) { _beneficiary.transfer(ethToRefund); } /// @notice Revert if commitmentsTotal exceeds the balance require(marketStatus.commitmentsTotal <= address(this).balance, "CrowdSale: The committed ETH exceeds the balance"); } /** * @notice Buy Tokens by commiting approved ERC20 tokens to this contract address. * @param _amount Amount of tokens to commit. */ function commitTokens(uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public { commitTokensFrom(msg.sender, _amount, readAndAgreedToMarketParticipationAgreement); } /** * @notice Checks how much is user able to commit and processes that commitment. * @dev Users must approve contract prior to committing tokens to auction. * @param _from User ERC20 address. * @param _amount Amount of approved ERC20 tokens. */ function commitTokensFrom( address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement ) public nonReentrant { require(address(paymentCurrency) != ETH_ADDRESS, "Crowdsale: Payment currency is not a token"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } uint256 tokensToTransfer = calculateCommitment(_amount); if (tokensToTransfer > 0) { _safeTransferFrom(paymentCurrency, msg.sender, tokensToTransfer); _addCommitment(_from, tokensToTransfer); } } /** * @notice Checks if the commitment does not exceed the goal of this sale. * @param _commitment Number of tokens to be commited. * @return committed The amount able to be purchased during a sale. */ function calculateCommitment(uint256 _commitment) public view returns (uint256 committed) { uint256 tokens = _getTokenAmount(_commitment); uint256 tokensCommited =_getTokenAmount(uint256(marketStatus.commitmentsTotal)); if ( tokensCommited.add(tokens) > uint256(marketInfo.totalTokens)) { return _getTokenPrice(uint256(marketInfo.totalTokens).sub(tokensCommited)); } return _commitment; } /** * @notice Updates commitment of the buyer and the amount raised, emits an event. * @param _addr Recipient of the token purchase. * @param _commitment Value in wei or token involved in the purchase. */ function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime), "Crowdsale: outside auction hours"); require(_addr != address(0), "Crowdsale: beneficiary is the zero address"); require(!marketStatus.finalized, "CrowdSale: Auction is finalized"); uint256 newCommitment = commitments[_addr].add(_commitment); if (marketStatus.usePointList) { require(IPointList(pointList).hasPoints(_addr, newCommitment)); } commitments[_addr] = newCommitment; /// @dev Update state. marketStatus.commitmentsTotal = BoringMath.to128(uint256(marketStatus.commitmentsTotal).add(_commitment)); emit AddedCommitment(_addr, _commitment); } function withdrawTokens() public { withdrawTokens(msg.sender); } /** * @notice Withdraws bought tokens, or returns commitment if the sale is unsuccessful. * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address payable beneficiary) public nonReentrant { if (auctionSuccessful()) { require(marketStatus.finalized, "Crowdsale: not finalized"); /// @dev Successful auction! Transfer claimed tokens. uint256 tokensToClaim = tokensClaimable(beneficiary); require(tokensToClaim > 0, "Crowdsale: no tokens to claim"); claimed[beneficiary] = claimed[beneficiary].add(tokensToClaim); _safeTokenPayment(auctionToken, beneficiary, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > uint256(marketInfo.endTime), "Crowdsale: auction has not finished yet"); uint256 accountBalance = commitments[beneficiary]; commitments[beneficiary] = 0; // Stop multiple withdrawals and free some gas _safeTokenPayment(paymentCurrency, beneficiary, accountBalance); } } /** * @notice Adjusts users commitment depending on amount already claimed and unclaimed tokens left. * @return claimerCommitment How many tokens the user is able to claim. */ function tokensClaimable(address _user) public view returns (uint256 claimerCommitment) { uint256 unclaimedTokens = IERC20(auctionToken).balanceOf(address(this)); claimerCommitment = _getTokenAmount(commitments[_user]); claimerCommitment = claimerCommitment.sub(claimed[_user]); if(claimerCommitment > unclaimedTokens){ claimerCommitment = unclaimedTokens; } } //-------------------------------------------------------- // Finalize Auction //-------------------------------------------------------- /** * @notice Manually finalizes the Crowdsale. * @dev Must be called after crowdsale ends, to do some extra finalization work. * Calls the contracts finalization function. */ function finalize() public nonReentrant { require( hasAdminRole(msg.sender) || wallet == msg.sender || hasSmartContractRole(msg.sender) || finalizeTimeExpired(), "Crowdsale: sender must be an admin" ); MarketStatus storage status = marketStatus; require(!status.finalized, "Crowdsale: already finalized"); MarketInfo storage info = marketInfo; require(info.totalTokens > 0, "Not initialized"); require(auctionEnded(), "Crowdsale: Has not finished yet"); if (auctionSuccessful()) { /// @dev Successful auction /// @dev Transfer contributed tokens to wallet. _safeTokenPayment(paymentCurrency, wallet, uint256(status.commitmentsTotal)); /// @dev Transfer unsold tokens to wallet. uint256 soldTokens = _getTokenAmount(uint256(status.commitmentsTotal)); uint256 unsoldTokens = uint256(info.totalTokens).sub(soldTokens); if(unsoldTokens > 0) { _safeTokenPayment(auctionToken, wallet, unsoldTokens); } } else { /// @dev Failed auction /// @dev Return auction tokens back to wallet. _safeTokenPayment(auctionToken, wallet, uint256(info.totalTokens)); } status.finalized = true; emit AuctionFinalized(); } /** * @notice Cancel Auction * @dev Admin can cancel the auction before it starts */ function cancelAuction() public nonReentrant { require(hasAdminRole(msg.sender)); MarketStatus storage status = marketStatus; require(!status.finalized, "Crowdsale: already finalized"); require( uint256(status.commitmentsTotal) == 0, "Crowdsale: Funds already raised" ); _safeTokenPayment(auctionToken, wallet, uint256(marketInfo.totalTokens)); status.finalized = true; emit AuctionCancelled(); } function tokenPrice() public view returns (uint256) { return uint256(marketPrice.rate); } function _getTokenPrice(uint256 _amount) internal view returns (uint256) { return _amount.mul(uint256(marketPrice.rate)).div(AUCTION_TOKEN_DECIMALS); } function getTokenAmount(uint256 _amount) public view returns (uint256) { _getTokenAmount(_amount); } /** * @notice Calculates the number of tokens to purchase. * @dev Override to extend the way in which ether is converted to tokens. * @param _amount Value in wei or token to be converted into tokens. * @return tokenAmount Number of tokens that can be purchased with the specified amount. */ function _getTokenAmount(uint256 _amount) internal view returns (uint256) { return _amount.mul(AUCTION_TOKEN_DECIMALS).div(uint256(marketPrice.rate)); } /** * @notice Checks if the sale is open. * @return isOpen True if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { return block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime); } /** * @notice Checks if the sale minimum amount was raised. * @return auctionSuccessful True if the commitmentsTotal is equal or higher than goal. */ function auctionSuccessful() public view returns (bool) { return uint256(marketStatus.commitmentsTotal) >= uint256(marketPrice.goal); } /** * @notice Checks if the sale has ended. * @return auctionEnded True if sold out or time has ended. */ function auctionEnded() public view returns (bool) { return block.timestamp > uint256(marketInfo.endTime) || _getTokenAmount(uint256(marketStatus.commitmentsTotal) + 1) >= uint256(marketInfo.totalTokens); } /** * @notice Checks if the sale has been finalised. * @return bool True if sale has been finalised. */ function finalized() public view returns (bool) { return marketStatus.finalized; } /** * @return True if 7 days have passed since the end of the auction */ function finalizeTimeExpired() public view returns (bool) { return uint256(marketInfo.endTime) + 7 days < block.timestamp; } //-------------------------------------------------------- // Documents //-------------------------------------------------------- function setDocument(string calldata _name, string calldata _data) external { require(hasAdminRole(msg.sender) ); _setDocument( _name, _data); } function setDocuments(string[] calldata _name, string[] calldata _data) external { require(hasAdminRole(msg.sender) ); uint256 numDocs = _name.length; for (uint256 i = 0; i < numDocs; i++) { _setDocument( _name[i], _data[i]); } } function removeDocument(string calldata _name) external { require(hasAdminRole(msg.sender)); _removeDocument(_name); } //-------------------------------------------------------- // Point Lists //-------------------------------------------------------- function setList(address _list) external { require(hasAdminRole(msg.sender)); _setList(_list); } function enableList(bool _status) external { require(hasAdminRole(msg.sender)); marketStatus.usePointList = _status; } function _setList(address _pointList) private { if (_pointList != address(0)) { pointList = _pointList; marketStatus.usePointList = true; } } //-------------------------------------------------------- // Setter Functions //-------------------------------------------------------- /** * @notice Admin can set start and end time through this function. * @param _startTime Auction start time. * @param _endTime Auction end time. */ function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "Crowdsale: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "Crowdsale: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "Crowdsale: start time is before current time"); require(_endTime > _startTime, "Crowdsale: end time must be older than start price"); require(marketStatus.commitmentsTotal == 0, "Crowdsale: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); } /** * @notice Admin can set auction price through this function. * @param _rate Price per token. * @param _goal Minimum amount raised and goal for the auction. */ function setAuctionPrice(uint256 _rate, uint256 _goal) external { require(hasAdminRole(msg.sender)); require(_goal > 0, "Crowdsale: goal is 0"); require(_rate > 0, "Crowdsale: rate is 0"); require(marketStatus.commitmentsTotal == 0, "Crowdsale: auction cannot have already started"); marketPrice.rate = BoringMath.to128(_rate); marketPrice.goal = BoringMath.to128(_goal); require(_getTokenAmount(_goal) <= uint256(marketInfo.totalTokens), "Crowdsale: minimum target exceeds hard cap"); emit AuctionPriceUpdated(_rate,_goal); } /** * @notice Admin can set the auction wallet through this function. * @param _wallet Auction wallet is where funds will be sent. */ function setAuctionWallet(address payable _wallet) external { require(hasAdminRole(msg.sender)); require(_wallet != address(0), "Crowdsale: wallet is the zero address"); wallet = _wallet; emit AuctionWalletUpdated(_wallet); } //-------------------------------------------------------- // Market Launchers //-------------------------------------------------------- function init(bytes calldata _data) external override payable { } /** * @notice Decodes and hands Crowdsale data to the initCrowdsale function. * @param _data Encoded data for initialization. */ function initMarket(bytes calldata _data) public override { ( address _funder, address _token, address _paymentCurrency, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, address _admin, address _pointList, address payable _wallet ) = abi.decode(_data, ( address, address, address, uint256, uint256, uint256, uint256, uint256, address, address, address ) ); initCrowdsale(_funder, _token, _paymentCurrency, _totalTokens, _startTime, _endTime, _rate, _goal, _admin, _pointList, _wallet); } /** * @notice Collects data to initialize the crowd sale. * @param _funder The address that funds the token for crowdsale. * @param _token Address of the token being sold. * @param _paymentCurrency The currency the crowdsale accepts for payment. Can be ETH or token address. * @param _totalTokens The total number of tokens to sell in crowdsale. * @param _startTime Crowdsale start time. * @param _endTime Crowdsale end time. * @param _rate Number of token units a buyer gets per wei or token. * @param _goal Minimum amount of funds to be raised in weis or tokens. * @param _admin Address that can finalize crowdsale. * @param _pointList Address that will manage auction approvals. * @param _wallet Address where collected funds will be forwarded to. * @return _data All the data in bytes format. */ function getCrowdsaleInitData( address _funder, address _token, address _paymentCurrency, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, address _admin, address _pointList, address payable _wallet ) external pure returns (bytes memory _data) { return abi.encode( _funder, _token, _paymentCurrency, _totalTokens, _startTime, _endTime, _rate, _goal, _admin, _pointList, _wallet ); } function getBaseInformation() external view returns( address, uint64, uint64, bool ) { return (auctionToken, marketInfo.startTime, marketInfo.endTime, marketStatus.finalized); } function getTotalTokens() external view returns(uint256) { return uint256(marketInfo.totalTokens); } } pragma solidity 0.6.12; /** * @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 () internal { _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: GPL-3.0-only pragma solidity 0.6.12; import "./MISOAdminAccess.sol"; /** * @notice Access Controls * @author Attr: BlockRocket.tech */ contract MISOAccessControls is MISOAdminAccess { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); /// @notice Events for adding and removing various roles event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event OperatorRoleGranted( address indexed beneficiary, address indexed caller ); event OperatorRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) public view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) public view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Used to check whether an address has the operator role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasOperatorRole(address _address) public view returns (bool) { return hasRole(OPERATOR_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } /** * @notice Grants the operator role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addOperatorRole(address _address) external { grantRole(OPERATOR_ROLE, _address); emit OperatorRoleGranted(_address, _msgSender()); } /** * @notice Removes the operator role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeOperatorRole(address _address) external { revokeRole(OPERATOR_ROLE, _address); emit OperatorRoleRemoved(_address, _msgSender()); } } pragma solidity 0.6.12; contract SafeTransfer { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Helper function to handle both ETH and ERC20 payments function _safeTokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _safeTransferETH(_to,_amount ); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Transfer helper from UniswapV2 Router function _safeApprove(address token, address to, uint 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: APPROVE_FAILED'); } /** * There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 * Im trying to make it a habit to put external calls last (reentrancy) * You can put this in an internal function if you like. */ function _safeTransfer( address token, address to, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)")) abi.encodeWithSelector(0xa9059cbb, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed } function _safeTransferFrom( address token, address from, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed } function _safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function _safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto import "./BoringERC20.sol"; contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } pragma solidity 0.6.12; import "../interfaces/IERC20.sol"; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "BoringMath: Div zero"); c = a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to16(uint256 a) internal pure returns (uint16 c) { require(a <= uint16(-1), "BoringMath: uint16 Overflow"); c = uint16(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath16 { function add(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title Standard implementation of ERC1643 Document management */ contract Documents { struct Document { uint32 docIndex; // Store the document name indexes uint64 lastModified; // Timestamp at which document details was last modified string data; // data of the document that exist off-chain } // mapping to store the documents details in the document mapping(string => Document) internal _documents; // mapping to store the document name indexes mapping(string => uint32) internal _docIndexes; // Array use to store all the document name present in the contracts string[] _docNames; // Document Events event DocumentRemoved(string indexed _name, string _data); event DocumentUpdated(string indexed _name, string _data); /** * @notice Used to attach a new document to the contract, or update the data or hash of an existing attached document * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always * @param _data Off-chain data of the document from where it is accessible to investors/advisors to read. */ function _setDocument(string calldata _name, string calldata _data) internal { require(bytes(_name).length > 0, "Zero name is not allowed"); require(bytes(_data).length > 0, "Should not be a empty data"); // Document storage document = _documents[_name]; if (_documents[_name].lastModified == uint64(0)) { _docNames.push(_name); _documents[_name].docIndex = uint32(_docNames.length); } _documents[_name] = Document(_documents[_name].docIndex, uint64(now), _data); emit DocumentUpdated(_name, _data); } /** * @notice Used to remove an existing document from the contract by giving the name of the document. * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always */ function _removeDocument(string calldata _name) internal { require(_documents[_name].lastModified != uint64(0), "Document should exist"); uint32 index = _documents[_name].docIndex - 1; if (index != _docNames.length - 1) { _docNames[index] = _docNames[_docNames.length - 1]; _documents[_docNames[index]].docIndex = index + 1; } _docNames.pop(); emit DocumentRemoved(_name, _documents[_name].data); delete _documents[_name]; } /** * @notice Used to return the details of a document with a known name (`string`). * @param _name Name of the document * @return string The data associated with the document. * @return uint256 the timestamp at which the document was last modified. */ function getDocument(string calldata _name) external view returns (string memory, uint256) { return ( _documents[_name].data, uint256(_documents[_name].lastModified) ); } /** * @notice Used to retrieve a full list of documents attached to the smart contract. * @return string List of all documents names present in the contract. */ function getAllDocuments() external view returns (string[] memory) { return _docNames; } /** * @notice Used to retrieve the total documents in the smart contract. * @return uint256 Count of the document names present in the contract. */ function getDocumentCount() external view returns (uint256) { return _docNames.length; } /** * @notice Used to retrieve the document name from index in the smart contract. * @return string Name of the document name. */ function getDocumentName(uint256 _index) external view returns (string memory) { require(_index < _docNames.length, "Index out of bounds"); return _docNames[_index]; } } pragma solidity 0.6.12; // ---------------------------------------------------------------------------- // White List interface // ---------------------------------------------------------------------------- interface IPointList { function isInList(address account) external view returns (bool); function hasPoints(address account, uint256 amount) external view returns (bool); function setPoints( address[] memory accounts, uint256[] memory amounts ) external; function initPointList(address accessControl) external ; } pragma solidity 0.6.12; interface IMisoMarket { function init(bytes calldata data) external payable; function initMarket( bytes calldata data ) external; function marketTemplate() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.6.12; import "../OpenZeppelin/access/AccessControl.sol"; contract MISOAdminAccess is AccessControl { /// @dev Whether access is initialised. bool private initAccess; /// @notice Events for adding and removing various roles. event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); /// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses. constructor() public { } /** * @notice Initializes access controls. * @param _admin Admins address. */ function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); require(_admin != address(0), "Incorrect input"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role. * @param _address EOA or contract being checked. * @return bool True if the account has the role or false if it does not. */ function hasAdminRole(address _address) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address. * @dev The sender must have the admin role. * @param _address EOA or contract receiving the new role. */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address. * @dev The sender must have the admin role. * @param _address EOA or contract affected. */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } } pragma solidity 0.6.12; import "../utils/EnumerableSet.sol"; import "../utils/Context.sol"; /** * @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; 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()); } } } pragma solidity 0.6.12; /** * @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; // 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]; } // 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)); } } pragma solidity 0.6.12; /* * @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; } } pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
Checks if the commitment does not exceed the goal of this sale. _commitment Number of tokens to be commited. return committed The amount able to be purchased during a sale./
function calculateCommitment(uint256 _commitment) public view returns (uint256 committed) { uint256 tokens = _getTokenAmount(_commitment); uint256 tokensCommited =_getTokenAmount(uint256(marketStatus.commitmentsTotal)); if ( tokensCommited.add(tokens) > uint256(marketInfo.totalTokens)) { return _getTokenPrice(uint256(marketInfo.totalTokens).sub(tokensCommited)); } return _commitment; }
473,086
pragma solidity ^0.5.2; // File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol interface intvoteinterface31 { //inject NONSTANDARD NAMING //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL82( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL81( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE48( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE79( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface ierc2016 { //inject NONSTANDARD NAMING function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol contract ownable56 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED0(address(0), _owner); } function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER65() { //inject NONSTANDARD NAMING require(ISOWNER85()); _; } function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED0(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP15(newOwner); } function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED0(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol contract reputation51 is ownable56 { //inject NONSTANDARD NAMING uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT94(block.number); } // Query balance and totalSupply in History function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT72(_owner, block.number); } function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT9(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT9(totalSupplyHistory, _blockNumber); } } function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF62(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount); emit MINT64(_user, _amount); return true; } function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF62(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned); emit BURN4(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol library safemath4 { //inject NONSTANDARD NAMING function MUL16(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 DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING using safemath4 for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER44(msg.sender, to, value); return true; } function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL97(msg.sender, spender, value); return true; } function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value); _TRANSFER44(from, to, value); emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB37(value); _balances[to] = _balances[to].ADD40(value); emit TRANSFER49(from, to, value); } function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD40(value); _balances[account] = _balances[account].ADD40(value); emit TRANSFER49(address(0), account, value); } function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB37(value); _balances[account] = _balances[account].SUB37(value); emit TRANSFER49(account, address(0), value); } function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value); _BURN11(account, value); emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING function BURN49(uint256 value) public { //inject NONSTANDARD NAMING _BURN11(msg.sender, value); } function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM86(from, value); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY28().ADD40(_amount) <= cap); _MINT14(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol library address8 { //inject NONSTANDARD NAMING function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING 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; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol pragma solidity ^0.5.2; library safeerc2019 { //inject NONSTANDARD NAMING using address8 for address; bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol contract avatar70 is ownable56 { //inject NONSTANDARD NAMING using safeerc2019 for address; string public orgName; daotoken36 public nativeToken; reputation51 public nativeReputation; event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER12(msg.sender, msg.value); } function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-low-level-calls (success, returnValue) = _contract.call(_data); emit GENERICCALL1(_contract, _data, success); } function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER8(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFER100(_to, _value); emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFEAPPROVE78(_spender, _value); emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value); return true; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol contract universalschemeinterface23 { //inject NONSTANDARD NAMING function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol contract globalconstraintinterface55 { //inject NONSTANDARD NAMING enum CallPhase { Pre, Post, PreAndPost } function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol interface controllerinterface59 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value, avatar70 _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING bytes32 public hashedParameters; // For other parameters. function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING bytes32 _hashedParameters ) public ONLYOWNER65 { hashedParameters = _hashedParameters; } function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)), "scheme is not registered"); return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol library ecdsa86 { //inject NONSTANDARD NAMING function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // 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))) } // 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) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol library realmath32 { //inject NONSTANDARD NAMING uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one87; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL16(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; // Do the squaring tempRealBase = MUL16(tempRealBase, tempRealBase); } // Return the final result. return uint216(realResult / real_one87); } function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87); } function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return uint256((uint256(realA) * uint256(realB)) >> real_fbits8); } function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one87) / uint256(realDenominator)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/SafeMath.sol // File: openzeppelin-solidity/contracts/math/Math.sol library math46 { //inject NONSTANDARD NAMING function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE32(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); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING using safemath4 for uint; using math46 for uint; using realmath32 for uint216; using realmath32 for uint256; using address8 for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices20 = 2; //inject NONSTANDARD NAMING uint256 constant public no97 = 2; //inject NONSTANDARD NAMING uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals ierc2016 public stakingToken; address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING constructor(ierc2016 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address24).ISCONTRACT13()) { stakingToken = ierc2016(gen_token_address24); } else { stakingToken = _stakingToken; } } modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE26(_proposalId)); _; } function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD40(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no97; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no97] = proposal.daoBountyRemain;//dao downstake on the proposal Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]]; staker.vote = no97; staker.amount = proposal.daoBountyRemain; emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted); require(_EXECUTE0(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100); require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS19( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH35(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION6(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes52) { lostReputation = proposal.preBoostedVotes[no97]; } else { lostReputation = proposal.preBoostedVotes[yes52]; } lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; if (staker.amount > 0) { if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]); if (staker.vote == yes52) { uint256 _totalStakes = ((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty; rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes; } else { rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes; if (organizations[proposal.organizationId] == _beneficiary) { //dao redeem it reward rewards[0] = rewards[0].SUB37(proposal.daoBounty); } } } staker.amount = 0; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]); rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100) .ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]); require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD40(rewards[2]) != 0) { votingmachinecallbacksinterface79(proposal.callbacks) .MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION31( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD40(rewards[2]) ); } } function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes52)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (votingmachinecallbacksinterface79(proposal.callbacks) .BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount); require( votingmachinecallbacksinterface79(proposal.callbacks) .STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW66(power); } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no97; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); if (_SCORE65(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE65(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no97])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE65(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB37(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals; } } emit EXECUTEPROPOSAL67( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL49(_proposalId, executionState); proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE55(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE0(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD40(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes52) { staker.amount4Bounty = staker.amount4Bounty.ADD40(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]); emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE0(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE0(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD40(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no97] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes52)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD40(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100; votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE0(_proposalId); } function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return proposal.stakes[yes52]/proposal.stakes[no97]; } function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING using ecdsa86 for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip71264 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(ierc2016 _stakingToken) public // solhint-disable-next-line no-empty-blocks genesisprotocollogic61(_stakingToken) { } function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE17(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip71264, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH91(); } address staker = delegationDigest.RECOVER59(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD40(1); return _STAKE17(_proposalId, _vote, _amount, staker); } function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE14(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE44(_proposalId, voter, _vote, _amount); } function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE0(_proposalId); } function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices20; } function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE26(_proposalId); } function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes52], proposals[_proposalId].preBoostedVotes[no97], proposals[_proposalId].stakes[yes52], proposals[_proposalId].stakes[no97] ); } function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes52, no97); } function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE65(_proposalId); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING struct ProposalInfo { uint256 blockNumber; // the proposal's block number avatar70 avatar; // the proposal's avatar address votingMachine; } modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine"); _; } //proposalId -> ProposalInfo mapping(bytes32 => ProposalInfo ) public proposalsInfo; function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; if (proposalsInfo[_proposalId].avatar == avatar70(0)) { return 0; } return _stakingToken.BALANCEOF62(address(avatar)); } function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber); } function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/GenericScheme.sol contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _callData, string _descriptionHash ); event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _genericCallReturnValue ); event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, int256 _param ); event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // Details of a voting proposal: struct CallProposal { bytes callData; bool exist; bool passed; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals; struct Parameters { intvoteinterface31 intVote; bytes32 voteParams; address contractToCall; } // A mapping from hashes to parameters (use to store a particular configuration on the controller) mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed == false, "cannot execute twice"); if (_decision == 1) { proposal.passed = true; EXECUTE34(_proposalId); } else { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); } emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision); return true; } function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)]; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed, "proposal must passed by voting machine"); proposal.exist = false; bytes memory genericCallReturnValue; bool success; controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8()); (success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar); if (success) { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue); } else { proposal.exist = true; } } function SETPARAMETERS19( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall); parameters[paramsHash].voteParams = _voteParams; parameters[paramsHash].intVote = _intVote; parameters[paramsHash].contractToCall = _contractToCall; return paramsHash; } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall)); } function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)]; intvoteinterface31 intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId] = CallProposal({ callData: _callData, exist: true, passed: false }); proposalsInfo[proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar, votingMachine:address(params.intVote) }); emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash); return proposalId; } function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall; } }
inject NONSTANDARD NAMING
function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool);
12,775,839
./full_match/80001/0xbB7Bf10aB05d0ed4B351C43197aB2Cbbd86c6abd/sources/contracts/pools/Pool.sol
Function to remove TCO2 addresses from internal whitelist erc20Addr accepts an array of contract addressescslither-disable-next-line uninitialized-local
function removeFromInternalWhiteList(address[] memory erc20Addr) external { onlyPoolOwner(); for (uint256 i; i < erc20Addr.length; ++i) { internalWhiteList[erc20Addr[i]] = false; emit InternalAddressRemovedFromWhitelist(erc20Addr[i]); } }
9,448,144
./full_match/80001/0x314420AB6D81b2FF31E25Fdd81aa13B1b643B64a/sources/contracts/DropSinglePhase.sol
Checks a request to claim NFTs against the active claim condition's criteria.
function BTVerifyClaim( address _claimer, bytes32[] memory proof, bytes32 root ) internal view returns (bool isOverride) { if(root != bytes32(0)) { (isOverride,) = MerkleProof.verify( proof,root,keccak256(abi.encodePacked(_claimer))); } return isOverride; }
871,589
./full_match/3/0x24550DB84186A1E3e5631630C2aA579CAC87FD59/sources/contracts/Faucet.sol
Limit withdrawal amount Send the amount to the address that requested it
function withdraw(uint withdraw_amount) public { require(withdraw_amount <= 100000000000000000); emit Withdrawal(msg.sender, withdraw_amount); }
14,206,842
./full_match/1/0x6E86583588D1b4c073A8b857D7388f67A3DC5f8F/sources/contracts/CyberAssassins.sol
Teams Regular Assassins Increase tracker and counter of regular assassin Mint regular assassin Super Assassins Increase tracker and counter of super assassin Mint super assassin
function reserveAssassins() external onlyOwner nonReentrant { require(!isReserved, "Already reserved"); uint256 tokenId; for (uint256 i = 0; i < _creators.length - 1; i++) { address wallet = _creators[i]; uint256 k; for (k = 0; k < 5; k++) { _tokenIdRegularTrackerTeam.increment(); _regularTokenCounter += 1; tokenId = _tokenIdRegularTrackerTeam.current(); _safeMint(wallet, tokenId); } for (k = 0; k < 2; k++) { _tokenIdSuperTrackerTeam.increment(); _superTokenCounter += 1; tokenId = _tokenIdSuperTrackerTeam.current() + 12000; _safeMint(wallet, tokenId); } _ultimateTokenCounter += 1; _safeMint(wallet, tokenId); } _tokenIdRegularTrackerTeam.increment(); tokenId = _tokenIdRegularTrackerTeam.current(); _safeMint(_creators[5], tokenId); _tokenIdRegularTrackerTeam.increment(); tokenId = _tokenIdRegularTrackerTeam.current(); _safeMint(_creators[5], tokenId); isReserved = true; }
9,804,373
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatAcclimator { function getApproved(uint256 tokenId) external view returns (address); function isApprovedForAll(address owner, address operator) external view returns (bool); function ownerOf(uint256 tokenId) external view returns (address); function balanceOf(address _owner) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IRegistry { function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function owner(bytes32 node) external view returns (address); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; } /** * @title MoonCatResolver * @notice ENS Resolver for MoonCat subdomains * @dev Auto-updates to point to the owner of that specific MoonCat */ contract MoonCatResolver { /* External Contracts */ IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69); IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); /* State */ mapping(bytes32 => uint256) internal NamehashMapping; // ENS namehash => Rescue ID of MoonCat mapping(uint256 => mapping(uint256 => bytes)) internal MultichainMapping; // Rescue ID of MoonCat => Multichain ID => value mapping(uint256 => mapping(string => string)) internal TextKeyMapping; // Rescue ID of MoonCat => text record key => value mapping(uint256 => bytes) internal ContentsMapping; // Rescue ID of MoonCat => content hash mapping(uint256 => address) internal lastAnnouncedAddress; // Rescue ID of MoonCat => address that was last emitted in an AddrChanged Event address payable public owner; bytes32 immutable public rootHash; string public ENSDomain; // Reference for the ENS domain this contract resolves string public avatarBaseURI = "eip155:1/erc721:0xc3f733ca98e0dad0386979eb96fb1722a1a05e69/"; uint64 public defaultTTL = 86400; // For string-matching on a specific text key uint256 constant internal avatarKeyLength = 6; bytes32 constant internal avatarKeyHash = keccak256("avatar"); /* Events */ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event TextChanged(bytes32 indexed node, string indexedKey, string key); event ContenthashChanged(bytes32 indexed node, bytes hash); /* Modifiers */ modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } modifier onlyMoonCatOwner (uint256 rescueOrder) { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); require(msg.sender == MCA.ownerOf(rescueOrder), "Not MoonCat's owner"); _; } /** * @dev Deploy resolver contract. */ constructor(bytes32 _rootHash, string memory _ENSDomain){ owner = payable(msg.sender); rootHash = _rootHash; ENSDomain = _ENSDomain; // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148) .claim(msg.sender); } /** * @dev Allow current `owner` to transfer ownership to another address */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Update the "avatar" value that gets set by default. */ function setAvatarBaseUrl(string calldata url) public onlyOwner { avatarBaseURI = url; } /** * @dev Update the default TTL value. */ function setDefaultTTL(uint64 newTTL) public onlyOwner { defaultTTL = newTTL; } /** * @dev Pass ownership of a subnode of the contract's root hash to the owner. */ function giveControl(bytes32 nodeId) public onlyOwner { IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e).setSubnodeOwner(rootHash, nodeId, owner); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } /** * @dev ERC165 support for ENS resolver interface * https://docs.ens.domains/contract-developer-guide/writing-a-resolver */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x01ffc9a7 // supportsInterface call itself || interfaceID == 0x3b3b57de // EIP137: ENS resolver || interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses || interfaceID == 0x59d1d43c // EIP634: ENS text records || interfaceID == 0xbc1c58d1 // EIP1577: contenthash ; } /** * @dev For a given ENS Node ID, return the Ethereum address it points to. * EIP137 core functionality */ function addr(bytes32 nodeID) public view returns (address) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); address actualOwner = MCA.ownerOf(rescueOrder); if ( MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) || actualOwner != lastAnnouncedAddress[rescueOrder] ) { return address(0); // Not Acclimated/Announced; return zero (per spec) } else { return lastAnnouncedAddress[rescueOrder]; } } /** * @dev For a given ENS Node ID, return an address on a different blockchain it points to. * EIP2304 functionality */ function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) { return bytes(''); // Not Acclimated; return zero (per spec) } if (coinType == 60) { // Ethereum address return abi.encodePacked(addr(nodeID)); } else { return MultichainMapping[rescueOrder][coinType]; } } /** * @dev For a given ENS Node ID, set it to point to an address on a different blockchain. * EIP2304 functionality */ function setAddr(bytes32 nodeID, uint256 coinType, bytes calldata newAddr) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setAddr(rescueOrder, coinType, newAddr); } /** * @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain. */ function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) { if (coinType == 60) { // Ethereum address announceMoonCat(rescueOrder); return; } emit AddressChanged(getSubdomainNameHash(uint2str(rescueOrder)), coinType, newAddr); emit AddressChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), coinType, newAddr); MultichainMapping[rescueOrder][coinType] = newAddr; } /** * @dev For a given ENS Node ID, return the value associated with a given text key. * If the key is "avatar", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned * EIP634 functionality */ function text(bytes32 nodeID, string calldata key) public view returns (string memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); string memory value = TextKeyMapping[rescueOrder][key]; if (bytes(value).length > 0) { // This value has been set explicitly; return that return value; } // Check if there's a default value for this key bytes memory keyBytes = bytes(key); if (keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){ // Avatar default return string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); } // No default; just return the empty string return value; } /** * @dev Update a text record for a specific subdomain. * EIP634 functionality */ function setText(bytes32 nodeID, string calldata key, string calldata value) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setText(rescueOrder, key, value); } /** * @dev Update a text record for subdomains owned by a specific MoonCat rescue order. */ function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) { bytes memory keyBytes = bytes(key); bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder)); bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))); if (bytes(value).length == 0 && keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){ // Avatar default string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); emit TextChanged(orderHash, key, avatarRecordValue); emit TextChanged(hexHash, key, avatarRecordValue); } else { emit TextChanged(orderHash, key, value); emit TextChanged(hexHash, key, value); } TextKeyMapping[rescueOrder][key] = value; } /** * @dev Get the "content hash" of a given subdomain. * EIP1577 functionality */ function contenthash(bytes32 nodeID) public view returns (bytes memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); return ContentsMapping[rescueOrder]; } /** * @dev Update the "content hash" of a given subdomain. * EIP1577 functionality */ function setContenthash(bytes32 nodeID, bytes calldata hash) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setContenthash(rescueOrder, hash); } /** * @dev Update the "content hash" of a given MoonCat's subdomains. */ function setContenthash(uint256 rescueOrder, bytes calldata hash) public onlyMoonCatOwner(rescueOrder) { emit ContenthashChanged(getSubdomainNameHash(uint2str(rescueOrder)), hash); emit ContenthashChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), hash); ContentsMapping[rescueOrder] = hash; } /** * @dev Set the TTL for a given MoonCat's subdomains. */ function setTTL(uint rescueOrder, uint64 newTTL) public onlyMoonCatOwner(rescueOrder) { IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); registry.setTTL(getSubdomainNameHash(uint2str(rescueOrder)), newTTL); registry.setTTL(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), newTTL); } /** * @dev Allow calling multiple functions on this contract in one transaction. */ function multicall(bytes[] calldata data) external returns(bytes[] memory results) { results = new bytes[](data.length); for (uint i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); require(success); results[i] = result; } return results; } /** * @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it. */ function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) { uint256 rescueOrder = NamehashMapping[nodeID]; if (rescueOrder == 0) { // Are we actually dealing with MoonCat #0? require( nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd4394902507c72856cf5950eaf9e7d5a // 0.ismymooncat.eth || nodeID == 0x1002474938c26fb23080c33c3db026c584b30ec6e7d3edf4717f3e01e627da26, // 0x00d658d50b.ismymooncat.eth "Unknown Node ID" ); } return rescueOrder; } /** * @dev Calculate the "namehash" of a specific domain, using the ENS standard algorithm. * The namehash of 'ismymooncat.eth' is 0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15 * The namehash of 'foo.ismymooncat.eth' is keccak256(0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15, keccak256('foo')) */ function getSubdomainNameHash(string memory subdomain) public view returns (bytes32) { return keccak256(abi.encodePacked(rootHash, keccak256(abi.encodePacked(subdomain)))); } /** * @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes. */ function mapMoonCat(uint256 rescueOrder) public { string memory orderSubdomain = uint2str(rescueOrder); string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder)); bytes32 orderHash = getSubdomainNameHash(orderSubdomain); bytes32 hexHash = getSubdomainNameHash(hexSubdomain); if (uint256(NamehashMapping[orderHash]) != 0) { // Already Mapped return; } NamehashMapping[orderHash] = rescueOrder; NamehashMapping[hexHash] = rescueOrder; if(MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) { // MoonCat is not Acclimated return; } IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); registry.setSubnodeRecord(rootHash, keccak256(bytes(orderSubdomain)), address(this), address(this), defaultTTL); registry.setSubnodeRecord(rootHash, keccak256(bytes(hexSubdomain)), address(this), address(this), defaultTTL); address moonCatOwner = MCA.ownerOf(rescueOrder); lastAnnouncedAddress[rescueOrder] = moonCatOwner; emit AddrChanged(orderHash, moonCatOwner); emit AddrChanged(hexHash, moonCatOwner); emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner)); emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner)); string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); emit TextChanged(orderHash, "avatar", avatarRecordValue); emit TextChanged(hexHash, "avatar", avatarRecordValue); } /** * @dev Announce a single MoonCat's (identified by Rescue Order) assigned address. */ function announceMoonCat(uint256 rescueOrder) public { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); address moonCatOwner = MCA.ownerOf(rescueOrder); lastAnnouncedAddress[rescueOrder] = moonCatOwner; bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder)); bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))); emit AddrChanged(orderHash, moonCatOwner); emit AddrChanged(hexHash, moonCatOwner); emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner)); emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner)); } /** * @dev Has an AddrChanged event been emitted for the current owner of a MoonCat (identified by Rescue Order)? */ function needsAnnouncing(uint256 rescueOrder) public view returns (bool) { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); return lastAnnouncedAddress[rescueOrder] != MCA.ownerOf(rescueOrder); } /** * @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing. */ function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) { uint256 balance = MCA.balanceOf(moonCatOwner); uint256 announceCount = 0; uint256[] memory tempRescueOrders = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){ tempRescueOrders[announceCount] = rescueOrder; announceCount++; } } uint256[] memory rescueOrders = new uint256[](announceCount); for (uint256 i = 0; i < announceCount; i++){ rescueOrders[i] = tempRescueOrders[i]; } return rescueOrders; } /** * @dev Convenience function to iterate through all MoonCats owned by sender to check if they need announcing. */ function needsAnnouncing() public view returns (uint256[] memory) { return needsAnnouncing(msg.sender); } /** * @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes. */ function mapMoonCats(uint256[] memory rescueOrders) public { for (uint256 i = 0; i < rescueOrders.length; i++) { address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrders[i]); } else if (lastAnnounced != MCA.ownerOf(rescueOrders[i])){ announceMoonCat(rescueOrders[i]); } } } /** * @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes. */ function mapMoonCats(address moonCatOwner) public { for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); address lastAnnounced = lastAnnouncedAddress[rescueOrder]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrder); } else if (lastAnnounced != moonCatOwner){ announceMoonCat(rescueOrder); } } } /** * @dev Convenience function to iterate through all MoonCats owned by the sender and announce or cache their subdomain hashes. */ function mapMoonCats() public { mapMoonCats(msg.sender); } /** * @dev Utility function to convert a bytes5 variable into a hexadecimal string. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol */ bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function bytes5ToHexString(bytes5 x) internal pure returns (string memory) { uint256 length = 5; uint256 value = uint256(uint40(x)); 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); } /** * @dev Utility function to convert a uint256 variable into a decimal string. */ function uint2str(uint value) internal pure returns (string memory) { 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); } }
Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes./
function mapMoonCats(address moonCatOwner) public { for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); address lastAnnounced = lastAnnouncedAddress[rescueOrder]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrder); announceMoonCat(rescueOrder); } } }
15,333,116
./full_match/44787/0xf6025239E9ced4d924177E9A6E855c608B1E815c/sources/contracts/CarbonPathToken.sol
Revoke Minter Role to the address Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./
function revokeMinter(address account) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CarbonPathToken: must be an admin"); _revokeRole(MINTER_ROLE, account); }
13,243,841
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/ICSTToken.sol"; import "./interfaces/ICSTFarmingProxy.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Implement CST's distrubution plan. contract CSTMinter is Ownable { using SafeMath for uint256; /// @notice Info of each pool of proxy. struct PoolInfo { address pool; // Address of farming contract. uint256 allocPoint; // How many allocation points assigned to this proxy. CSTs to distribute per block. uint256 lastRewardBlock; // Last block number that CSTs distribution occurs. } ICSTToken public cstToken; /// @notice Dev address. address public devaddr; /// @notice CST tokens created per block. uint256 public tokenPerBlock = 10_833_333_333_333_333_333; // 10.833333 cst/block /// @notice Info of each pool of proxy. mapping(address => mapping(address => PoolInfo)) public poolInfo; /// @notice Save proxy address whether exists. mapping(address => mapping(address => bool)) public proxyTokens; /// @notice Save proxy's address in array. address[] public proxyAddresses; /// @notice Save pool's address in array. mapping(address => address[]) public poolsAddress; /// @notice Save proxy whether exists. mapping(address => bool) public proxyExists; /// @notice Total allocation poitns. Must be the sum of all allocation points in all proxys. uint256 public totalAllocPoint = 0; /// @notice The block number when CST mining starts. uint256 public startBlock; /// @notice Halving Period in blocks. uint256 public halvingPeriod = 2_628_000; /// @notice Halving coefficient. uint256 public HALVING_COEFFICIENT = 1_189_207_115_002_721_024; event UpdateProxyInfo( address _farmingProxy, address _pool, uint256 _allocPoint, uint256 _totalAllocPoint ); event UpdateToken(address _tokenAddress); event SetHalvingPeriod(uint256 _block); event SetDevAddress(address _dev); event MintCST( address proxy, address pool, uint256 lastRewardBock, uint256 blockNumber, uint256 amount ); event PhaseChanged(address pool, uint256 phase, uint256 totalSupply); constructor( address _devaddr, uint256 _startBlock, address ownerAddress ) { require( _devaddr != address(0), "CSTMinter: dev address can't be 0 address" ); devaddr = _devaddr; startBlock = _startBlock; transferOwnership(ownerAddress); } function setToken(ICSTToken _token) public onlyOwner { require(address(_token) != address(0), "CSTMinter: no 0 address"); cstToken = _token; emit UpdateToken(address(_token)); } function setHalvingPeriod(uint256 _block) public onlyOwner { halvingPeriod = _block; emit SetHalvingPeriod(_block); } /// @notice Owner should add proxy first, then proxy can add its pools. /// @param _farmingProxy Proxy's address function addProxy(address _farmingProxy) public onlyOwner { require(_farmingProxy != address(0), "CSTMinter: no 0 address"); require( !proxyExists[_farmingProxy], "CSTMinter: _farmingProxy is exists." ); proxyAddresses.push(_farmingProxy); proxyExists[_farmingProxy] = true; } /// @notice Add a new proxy. Can only be called by the owner. /// @param _allocPoint Proxy's allocation's weight. /// @param _poolAddress A pool of the proxy. function add(uint256 _allocPoint, address _poolAddress) public { require(proxyExists[msg.sender], "CSTMinter: only proxy contract"); require(_poolAddress != address(0), "CSTMinter: no 0 address"); require( !proxyTokens[msg.sender][_poolAddress], "CSTMinter: _farmingProxy and pool already exist" ); proxyTokens[msg.sender][_poolAddress] = true; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); PoolInfo memory pInfo = poolInfo[msg.sender][_poolAddress]; pInfo.pool = _poolAddress; pInfo.allocPoint = _allocPoint; pInfo.lastRewardBlock = lastRewardBlock; poolInfo[msg.sender][_poolAddress] = pInfo; poolsAddress[msg.sender].push(_poolAddress); emit UpdateProxyInfo( msg.sender, _poolAddress, _allocPoint, totalAllocPoint ); } /// @notice Update the given proxy's CST allocation point. Can only be called by the owner. /// @param _poolAddress A pool of the proxy. /// @param _allocPoint Proxy's allocation's weight. function set(address _poolAddress, uint256 _allocPoint) public { require(proxyExists[msg.sender], "CSTMinter: only proxy contract"); require(_poolAddress != address(0), "CSTMinter: no 0 address"); totalAllocPoint = totalAllocPoint .sub(poolInfo[msg.sender][_poolAddress].allocPoint) .add(_allocPoint); poolInfo[msg.sender][_poolAddress].allocPoint = _allocPoint; emit UpdateProxyInfo( msg.sender, _poolAddress, _allocPoint, totalAllocPoint ); } function massUpdateProxyForOwner() public onlyOwner { for (uint256 i; i < proxyAddresses.length; i++) { ICSTFarmingProxy(proxyAddresses[i]).massUpdate(); } } function massUpdateProxy() public { require(proxyExists[msg.sender], "CSTMinter: only proxy contract"); for (uint256 i; i < proxyAddresses.length; i++) { ICSTFarmingProxy(proxyAddresses[i]).massUpdate(); } } function _phase(uint256 blockNumber) internal view returns (uint256) { if (halvingPeriod == 0) { return 0; } if (blockNumber > startBlock) { return (blockNumber.sub(startBlock).sub(1)).div(halvingPeriod); } return 0; } /// @notice At what phase function phase() public view returns (uint256) { return _phase(block.number); } /// @notice Get proxy's amount of total reward /// @param _proxyAddress the proxy's address. /// @param _poolAddress A pool of the proxy. /// @return return the amount of bst should be mint. function getReward(address _proxyAddress, address _poolAddress) public view returns (uint256) { PoolInfo storage pool = poolInfo[_proxyAddress][_poolAddress]; if (block.number <= pool.lastRewardBlock) { return 0; } uint256 _lastRewardBlock = pool.lastRewardBlock; uint256 blockReward = 0; uint256 _lastPhase = _phase(_lastRewardBlock); uint256 _currPhase = _phase(block.number); uint256 _bstPerBlock = tokenPerBlock; uint256 i = 1; while (i <= _lastPhase) { // calculate out lastPhase _bstPerBlock _bstPerBlock = _bstPerBlock.mul(10**18).div(HALVING_COEFFICIENT); i++; } // If it crosses the cycle while (_lastPhase < _currPhase) { _lastPhase++; // Get the last block of the previous cycle uint256 r = _lastPhase.mul(halvingPeriod).add(startBlock); // Get rewards from previous periods blockReward = blockReward.add( r .sub(_lastRewardBlock) .mul(_bstPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint) ); _bstPerBlock = _bstPerBlock.mul(10**18).div(HALVING_COEFFICIENT); _lastRewardBlock = r; } blockReward = blockReward.add( (block.number.sub(_lastRewardBlock)) .mul(_bstPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint) ); return blockReward; } /// @notice mint bst according options /// @param _pid proxy's address /// @param _pool pool's address. function mint_(address _pid, address _pool) internal returns (uint256) { PoolInfo storage pInfo = poolInfo[_pid][_pool]; uint256 _lastRewardBlock = pInfo.lastRewardBlock; if (block.number <= pInfo.lastRewardBlock) { return 0; } uint256 _lastPhase = _phase(_lastRewardBlock); uint256 _currPhase = _phase(block.number); if (_currPhase > _lastPhase) { emit PhaseChanged(_pool, _currPhase, cstToken.totalSupply()); } uint256 tokenReward = getReward(_pid, _pool); cstToken.mint(devaddr, tokenReward.div(10)); cstToken.mint(_pid, tokenReward); pInfo.lastRewardBlock = block.number; emit MintCST(_pid, _pool, _lastRewardBlock, block.number, tokenReward); return tokenReward; } /// @dev Update pool's lastRewardBlock to block.number /// @param pool Pool's address function updateLastRewardBlock(address pool) public { require(proxyTokens[msg.sender][pool], "CSTMinter: only farmingProxy"); PoolInfo storage pInfo = poolInfo[msg.sender][pool]; uint256 _lastRewardBlock = pInfo.lastRewardBlock; uint256 _lastPhase = _phase(_lastRewardBlock); uint256 _currPhase = _phase(block.number); if (_currPhase > _lastPhase) { emit PhaseChanged(pool, _currPhase, cstToken.totalSupply()); } poolInfo[msg.sender][pool].lastRewardBlock = block.number; } /// @notice mint bst according options /// @param pool pool's address. function mint(address pool) external returns (uint256) { require(proxyExists[msg.sender], "CSTMinter: only proxy contract"); require( proxyTokens[msg.sender][pool], "CSTMinter: proxy and pool no exists." ); return mint_(msg.sender, pool); } /// @notice Update dev address by the previous dev. function dev(address _devaddr) public onlyOwner { require( _devaddr != address(0), "CSTMinter: dev address can't be 0 address" ); devaddr = _devaddr; emit SetDevAddress(_devaddr); } function getTokenAddress() external view returns (address) { return address(cstToken); } function getStartBlock() external view returns (uint256) { return startBlock; } function getPoolInfo(address _proxy, address _pool) external view returns (uint256 _allocPoint, uint256 _lastRewardBlock) { _allocPoint = poolInfo[_proxy][_pool].allocPoint; _lastRewardBlock = poolInfo[_proxy][_pool].lastRewardBlock; } }
Owner should add proxy first, then proxy can add its pools. _farmingProxy Proxy's address
function addProxy(address _farmingProxy) public onlyOwner { require(_farmingProxy != address(0), "CSTMinter: no 0 address"); require( !proxyExists[_farmingProxy], "CSTMinter: _farmingProxy is exists." ); proxyAddresses.push(_farmingProxy); proxyExists[_farmingProxy] = true; }
5,381,786
pragma solidity ^0.4.25; // 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/math/SafeMath.sol"; contract ExerciseC6C { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct Profile { string id; bool isRegistered; bool isAdmin; uint256 sales; uint256 bonus; address wallet; } address private contractOwner; // Account used to deploy contract mapping(string => Profile) employees; // Mapping for storing employees mapping(address => uint256) private authorizedContracts; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // No events /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; } /********************************************************************************************/ /* 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 "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier isCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "The caller is not authorized"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Check if an employee is registered * * @return A bool that indicates if the employee is registered */ function isEmployeeRegistered ( string id ) external view returns (bool) { return employees[id].isRegistered; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function registerEmployee ( string id, bool isAdmin, address wallet ) external requireContractOwner { require(!employees[id].isRegistered, "Employee is already registered."); employees[id] = Profile({ id : id, isRegistered : true, isAdmin : isAdmin, sales : 0, bonus : 0, wallet : wallet }); } function getEmployeeBonus ( string id ) external view requireContractOwner returns (uint256) { return employees[id].bonus; } function updateEmployee ( string id, uint256 sales, uint256 bonus ) external { require(employees[id].isRegistered, "Employee is not registered."); employees[id].sales = employees[id].sales.add(sales); employees[id].bonus = employees[id].bonus.add(bonus); } function authorizeContract(address _address) external requireContractOwner { authorizedContracts[_address] = 1; } function deauthorizeContract(address _address) external requireContractOwner { delete authorizedContracts[_address]; } }
Check if an employee is registered return A bool that indicates if the employee is registered/
function isEmployeeRegistered ( string id ) external view returns (bool) { return employees[id].isRegistered; }
12,762,637
./full_match/888/0x87332A42bd65cb9A60975fbB705fB6522D12bc05/sources/contracts/gpk/GpkDelegateV2.sol
function for dest storeman set check status for encSij groupId storeman group id roundIndex group negotiate round curveIndex singnature curve index src src storeman address isValid whether encSij is valid
function setCheckStatus(bytes32 groupId, uint16 roundIndex, uint8 curveIndex, address src, bool isValid) external { GpkTypes.Group storage group = groupMap[groupId]; checkValid(group, roundIndex, curveIndex, GpkTypes.GpkStatus.Negotiate, true, true, src); GpkTypes.Round storage round = group.roundMap[roundIndex][curveIndex]; GpkTypes.Src storage s = round.srcMap[src]; GpkTypes.Dest storage d = s.destMap[msg.sender]; require(d.encSij.length != 0, "Not ready"); require(d.checkStatus == GpkTypes.CheckStatus.Init, "Duplicate"); d.checkTime = now; emit SetCheckStatusLogger(groupId, roundIndex, curveIndex, src, msg.sender, isValid); if (isValid) { d.checkStatus = GpkTypes.CheckStatus.Valid; s.checkValidCount++; round.checkValidCount++; if (round.checkValidCount >= group.smNumber ** 2) { round.status = GpkTypes.GpkStatus.Complete; round.statusTime = now; tryComplete(groupId, smg); } d.checkStatus = GpkTypes.CheckStatus.Invalid; } }
13,223,762
// SPDX-License-Identifier: MIT pragma solidity 0.6.10; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Ownable.sol"; import "./erc1820/ERC1820Client.sol"; import "./erc1820/ERC1820Implementer.sol"; import "./extensions/IAmpTokensSender.sol"; import "./extensions/IAmpTokensRecipient.sol"; import "./partitions/IAmpPartitionStrategyValidator.sol"; import "./partitions/lib/PartitionUtils.sol"; import "./codes/ErrorCodes.sol"; interface ISwapToken { function allowance(address owner, address spender) external view returns (uint256 remaining); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } /** * @title Amp * @notice Amp is an ERC20 compatible collateral token designed to support * multiple classes of collateralization systems. * @dev The Amp token contract includes the following features: * * Partitions * Tokens can be segmented within a given address by "partition", which in * practice is a 32 byte identifier. These partitions can have unique * permissions globally, through the using of partition strategies, and * locally, on a per address basis. The ability to create the sub-segments * of tokens and assign special behavior gives collateral managers * flexibility in how they are implemented. * * Operators * Inspired by ERC777, Amp allows token holders to assign "operators" on * all (or any number of partitions) of their tokens. Operators are allowed * to execute transfers on behalf of token owners without the need to use the * ERC20 "allowance" semantics. * * Transfers with Data * Inspired by ERC777, Amp transfers can include arbitrary data, as well as * operator data. This data can be used to change the partition of tokens, * be used by collateral manager hooks to validate a transfer, be propagated * via event to an off chain system, etc. * * Token Transfer Hooks on Send and Receive * Inspired by ERC777, Amp uses the ERC1820 Registry to allow collateral * manager implementations to register hooks to be called upon sending to * or transferring from the collateral manager's address or, using partition * strategies, owned partition space. The hook implementations can be used * to validate transfer properties, gate transfers, emit custom events, * update local state, etc. * * Collateral Management Partition Strategies * Amp is able to define certain sets of partitions, identified by a 4 byte * prefix, that will allow special, custom logic to be executed when transfers * are made to or from those partitions. This opens up the possibility of * entire classes of collateral management systems that would not be possible * without it. * * These features give collateral manager implementers flexibility while * providing a consistent, "collateral-in-place", interface for interacting * with collateral systems directly through the Amp contract. */ contract Amp is IERC20, ERC1820Client, ERC1820Implementer, ErrorCodes, Ownable { using SafeMath for uint256; /**************************************************************************/ /********************** ERC1820 Interface Constants ***********************/ /** * @dev AmpToken interface label. */ string internal constant AMP_INTERFACE_NAME = "AmpToken"; /** * @dev ERC20Token interface label. */ string internal constant ERC20_INTERFACE_NAME = "ERC20Token"; /** * @dev AmpTokensSender interface label. */ string internal constant AMP_TOKENS_SENDER = "AmpTokensSender"; /** * @dev AmpTokensRecipient interface label. */ string internal constant AMP_TOKENS_RECIPIENT = "AmpTokensRecipient"; /** * @dev AmpTokensChecker interface label. */ string internal constant AMP_TOKENS_CHECKER = "AmpTokensChecker"; /**************************************************************************/ /*************************** Token properties *****************************/ /** * @dev Token name (Amp). */ string internal _name; /** * @dev Token symbol (Amp). */ string internal _symbol; /** * @dev Total minted supply of token. This will increase comensurately with * successful swaps of the swap token. */ uint256 internal _totalSupply; /** * @dev The granularity of the token. Hard coded to 1. */ uint256 internal constant _granularity = 1; /**************************************************************************/ /***************************** Token mappings *****************************/ /** * @dev Mapping from tokenHolder to balance. This reflects the balance * across all partitions of an address. */ mapping(address => uint256) internal _balances; /**************************************************************************/ /************************** Partition mappings ****************************/ /** * @dev List of active partitions. This list reflects all partitions that * have tokens assigned to them. */ bytes32[] internal _totalPartitions; /** * @dev Mapping from partition to their index. */ mapping(bytes32 => uint256) internal _indexOfTotalPartitions; /** * @dev Mapping from partition to global balance of corresponding partition. */ mapping(bytes32 => uint256) public totalSupplyByPartition; /** * @dev Mapping from tokenHolder to their partitions. */ mapping(address => bytes32[]) internal _partitionsOf; /** * @dev Mapping from (tokenHolder, partition) to their index. */ mapping(address => mapping(bytes32 => uint256)) internal _indexOfPartitionsOf; /** * @dev Mapping from (tokenHolder, partition) to balance of corresponding * partition. */ mapping(address => mapping(bytes32 => uint256)) internal _balanceOfByPartition; /** * @notice Default partition of the token. * @dev All ERC20 operations operate solely on this partition. */ bytes32 public constant defaultPartition = 0x0000000000000000000000000000000000000000000000000000000000000000; /** * @dev Zero partition prefix. Partitions with this prefix can not have * a strategy assigned, and partitions with a different prefix must have one. */ bytes4 internal constant ZERO_PREFIX = 0x00000000; /**************************************************************************/ /***************************** Operator mappings **************************/ /** * @dev Mapping from (tokenHolder, operator) to authorized status. This is * specific to the token holder. */ mapping(address => mapping(address => bool)) internal _authorizedOperator; /**************************************************************************/ /********************** Partition operator mappings ***********************/ /** * @dev Mapping from (partition, tokenHolder, spender) to allowed value. * This is specific to the token holder. */ mapping(bytes32 => mapping(address => mapping(address => uint256))) internal _allowedByPartition; /** * @dev Mapping from (tokenHolder, partition, operator) to 'approved for * partition' status. This is specific to the token holder. */ mapping(address => mapping(bytes32 => mapping(address => bool))) internal _authorizedOperatorByPartition; /**************************************************************************/ /********************** Collateral Manager mappings ***********************/ /** * @notice Collection of registered collateral managers. */ address[] public collateralManagers; /** * @dev Mapping of collateral manager addresses to registration status. */ mapping(address => bool) internal _isCollateralManager; /**************************************************************************/ /********************* Partition Strategy mappings ************************/ /** * @notice Collection of reserved partition strategies. */ bytes4[] public partitionStrategies; /** * @dev Mapping of partition strategy flag to registration status. */ mapping(bytes4 => bool) internal _isPartitionStrategy; /**************************************************************************/ /***************************** Swap storage *******************************/ /** * @notice Swap token address. Immutable. */ ISwapToken public swapToken; /** * @notice Swap token graveyard address. * @dev This is the address that the incoming swapped tokens will be * forwarded to upon successfully minting Amp. */ address public constant swapTokenGraveyard = 0x000000000000000000000000000000000000dEaD; /**************************************************************************/ /** EVENTS ****************************************************************/ /**************************************************************************/ /**************************************************************************/ /**************************** Transfer Events *****************************/ /** * @notice Emitted when a transfer has been successfully completed. * @param fromPartition The partition from which tokens were transferred. * @param operator The address that initiated the transfer. * @param from The address from which the tokens were transferred. * @param to The address to which the tokens were transferred. * @param value The amount of tokens transferred. * @param data Additional metadata included with the transfer. Can include * the partition to which the tokens were transferred, if different than * `fromPartition`. * @param operatorData Additional metadata included with the transfer. Typically used by * partition strategies and collateral managers to authorize transfers. */ event TransferByPartition( bytes32 indexed fromPartition, address operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); /** * @notice Emitted when a transfer has been successfully completed and the * tokens that were transferred have changed partitions. * @param fromPartition The partition from which the tokens were transferred. * @param toPartition The partition to which the tokens were transferred. * @param value The amount of tokens transferred. */ event ChangedPartition( bytes32 indexed fromPartition, bytes32 indexed toPartition, uint256 value ); /**************************************************************************/ /**************************** Operator Events *****************************/ /** * @notice Emitted when a token holder authorizes an address to transfer tokens on its behalf * from a particular partition. * @param partition The partition of the tokens from which the holder has authorized the * `spender` to transfer. * @param owner The token holder. * @param spender The operator for which the `owner` has authorized the allowance. * @param value The amount of tokens authorized for transfer. */ event ApprovalByPartition( bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value ); /** * @notice Emitted when a token holder has authorized an operator to transfer tokens on the * behalf of the holder across all partitions. * @param operator The address that was authorized to transfer tokens on * behalf of the `tokenHolder`. * @param tokenHolder The address that authorized the `operator` to transfer * their tokens. */ event AuthorizedOperator(address indexed operator, address indexed tokenHolder); /** * @notice Emitted when a token holder has deauthorized an operator from * transferring tokens on behalf of the holder. * @dev Note that this applies an account-wide authorization change, and does not reflect any * change in the authorization for a particular partition. * @param operator The address that was deauthorized from transferring tokens * on behalf of the `tokenHolder`. * @param tokenHolder The address that revoked the `operator`'s authorization * to transfer their tokens. */ event RevokedOperator(address indexed operator, address indexed tokenHolder); /** * @notice Emitted when a token holder has authorized an operator to transfer * tokens on behalf of the holder from a particular partition. * @param partition The partition from which the `operator` is authorized to transfer. * @param operator The address authorized to transfer tokens on * behalf of the `tokenHolder`. * @param tokenHolder The address that authorized the `operator` to transfer * tokens held in partition `partition`. */ event AuthorizedOperatorByPartition( bytes32 indexed partition, address indexed operator, address indexed tokenHolder ); /** * @notice Emitted when a token holder has deauthorized an operator from * transferring held tokens from a specific partition. * @param partition The partition for which the `operator` was deauthorized for token transfer * on behalf of the `tokenHolder`. * @param operator The address that was deauthorized from transferring * tokens on behalf of the `tokenHolder`. * @param tokenHolder The address that revoked the `operator`'s permission * to transfer held tokens from `partition`. */ event RevokedOperatorByPartition( bytes32 indexed partition, address indexed operator, address indexed tokenHolder ); /**************************************************************************/ /********************** Collateral Manager Events *************************/ /** * @notice Emitted when a collateral manager has been registered. * @param collateralManager The address of the collateral manager. */ event CollateralManagerRegistered(address collateralManager); /**************************************************************************/ /*********************** Partition Strategy Events ************************/ /** * @notice Emitted when a new partition strategy validator is set. * @param flag The 4 byte prefix of the partitions that the strategy affects. * @param name The name of the interface implemented by the partition strategy. * @param implementation The address of the partition strategy hook * implementation. */ event PartitionStrategySet(bytes4 flag, string name, address indexed implementation); // ************** Mint & Swap ************** /** * @notice Emitted when tokens are minted, which only occurs as the result of token swap. * @param operator Address that executed the swap, resulting in tokens being minted * @param to Address that received the newly minted tokens. * @param value Amount of tokens minted. * @param data Additional metadata. Unused; required for interface compatibility. */ event Minted(address indexed operator, address indexed to, uint256 value, bytes data); /** * @notice Emitted when tokens are swapped as part of the minting process. * @param operator Address that executed the swap. * @param from Address whose source swap tokens were burned, and for which Amp tokens were * minted. * @param value Amount of tokens swapped into Amp. */ event Swap(address indexed operator, address indexed from, uint256 value); /**************************************************************************/ /** CONSTRUCTOR ***********************************************************/ /**************************************************************************/ /** * @notice Initialize Amp, initialize the default partition, and register the * contract implementation in the global ERC1820Registry. * @param _swapTokenAddress_ The address of the ERC-20 token that is set to be * swappable for Amp. * @param _name_ Name of the token to be initialized. * @param _symbol_ Symbol of the token to be initialized. */ constructor( address _swapTokenAddress_, string memory _name_, string memory _symbol_ ) public { // "Swap token cannot be 0 address" require(_swapTokenAddress_ != address(0), EC_5A_INVALID_SWAP_TOKEN_ADDRESS); swapToken = ISwapToken(_swapTokenAddress_); _name = _name_; _symbol = _symbol_; _totalSupply = 0; // Add the default partition to the total partitions on deploy _addPartitionToTotalPartitions(defaultPartition); // Register contract in ERC1820 registry ERC1820Client.setInterfaceImplementation(AMP_INTERFACE_NAME, address(this)); ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this)); // Indicate token verifies Amp and ERC20 interfaces ERC1820Implementer._setInterface(AMP_INTERFACE_NAME); ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); } /**************************************************************************/ /** EXTERNAL FUNCTIONS (ERC20) ********************************************/ /**************************************************************************/ /** * @notice Retrieves the total number of minted tokens. * @return uint256 containing the total number of minted tokens. */ function totalSupply() external override view returns (uint256) { return _totalSupply; } /** * @notice Retrieves the balance of the account with address `_tokenHolder` across all partitions. * @dev Note that this figure should not be used as the arbiter of the amount a token holder * will successfully be able to send via the ERC-20 compatible `Amp.transfer` method. In order * to get that figure, use `Amp.balanceOfByPartition` to get the balance of the default * partition. * @param _tokenHolder Address for which the balance is returned. * @return uint256 containing the amount of tokens held by `_tokenHolder` * across all partitions. */ function balanceOf(address _tokenHolder) external override view returns (uint256) { return _balances[_tokenHolder]; } /** * @notice Transfers an amount of tokens to the specified address. * @dev Note that this only transfers from the `msg.sender` address's default partition. * To transfer from other partitions, use function `Amp.transferByPartition`. * @param _to The address to which the tokens should be transferred. * @param _value The amount of tokens to be transferred. * @return bool indicating whether the operation was successful. */ function transfer(address _to, uint256 _value) external override returns (bool) { _transferByDefaultPartition(msg.sender, msg.sender, _to, _value, ""); return true; } /** * @notice Transfers an amount of tokens between two accounts. * @dev Note that this only transfers from the `_from` address's default partition. * To transfer from other partitions, use function `Amp.transferByPartition`. * @param _from The address from which the tokens are to be transferred. * @param _to The address to which the tokens are to be transferred. * @param _value The amount of tokens to be transferred. * @return bool indicating whether the operation was successful. */ function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { _transferByDefaultPartition(msg.sender, _from, _to, _value, ""); return true; } /** * @notice Retrieves the allowance of tokens that has been granted by `_owner` to * `_spender` for the default partition. * @dev Note that this only returns the allowance of the `_owner` address's default partition. * To retrieve the allowance for a different partition, use function `Amp.allowanceByPartition`. * @param _owner The address holding the authorized tokens. * @param _spender The address authorized to transfer the tokens from `_owner`. * @return uint256 specifying the amount of tokens available for the `_spender` to transfer * from the `_owner`'s default partition. */ function allowance(address _owner, address _spender) external override view returns (uint256) { return _allowedByPartition[defaultPartition][_owner][_spender]; } /** * @notice Sets an allowance for an address to transfer an amount of tokens on behalf of the * caller. * @dev Note that this only affects the `msg.sender` address's default partition. * To approve transfers from other partitions, use function `Amp.approveByPartition`. * * This method is required for ERC-20 compatibility, but is subject to the race condition * described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. * * Functions `Amp.increaseAllowance` and `Amp.decreaseAllowance` should be used instead. * @param _spender The address which is authorized to transfer tokens from default partition * of `msg.sender`. * @param _value The amount of tokens to be authorized. * @return bool indicating if the operation was successful. */ function approve(address _spender, uint256 _value) external override returns (bool) { _approveByPartition(defaultPartition, msg.sender, _spender, _value); return true; } /** * @notice Increases the allowance granted to `_spender` by the caller. * @dev This is an alternative to `Amp.approve` that can be used as a mitigation for * the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. * * Note that this only affects the `msg.sender` address's default partition. * To increase the allowance for other partitions, use function * `Amp.increaseAllowanceByPartition`. * * #### Requirements: * - `_spender` cannot be the zero address. * @param _spender The account authorized to transfer the tokens. * @param _addedValue Additional amount of the `msg.sender`'s tokens `_spender` * is allowed to transfer. * @return bool indicating if the operation was successful. */ function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) { _approveByPartition( defaultPartition, msg.sender, _spender, _allowedByPartition[defaultPartition][msg.sender][_spender].add(_addedValue) ); return true; } /** * @notice Decreases the allowance granted to `_spender` by the caller. * @dev This is an alternative to `Amp.approve` that can be used as a mitigation for * the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. * * Note that this only affects the `msg.sender` address's default partition. * To decrease the allowance for other partitions, use function * `decreaseAllowanceByPartition`. * * #### Requirements: * - `_spender` cannot be the zero address. * - `_spender` must have an allowance for the caller of at least `_subtractedValue`. * @param _spender Account whose authorization to transfer tokens is to be decreased. * @param _subtractedValue Amount by which the authorization for `_spender` to transfer tokens * held by `msg.sender`'s account is to be decreased. * @return bool indicating if the operation was successful. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) { _approveByPartition( defaultPartition, msg.sender, _spender, _allowedByPartition[defaultPartition][msg.sender][_spender].sub( _subtractedValue ) ); return true; } /**************************************************************************/ /** EXTERNAL FUNCTIONS (AMP) **********************************************/ /**************************************************************************/ /******************************** Swap ***********************************/ /** * @notice Exchanges an amount of source swap tokens from the contract defined at deployment * for the equivalent amount of Amp tokens. * @dev Requires the `_from` account to have granted the Amp contract an allowance of swap * tokens no greater than their balance. * @param _from Token holder whose swap tokens will be exchanged for Amp tokens. */ function swap(address _from) public { uint256 amount = swapToken.allowance(_from, address(this)); require(amount > 0, EC_53_INSUFFICIENT_ALLOWANCE); require( swapToken.transferFrom(_from, swapTokenGraveyard, amount), EC_60_SWAP_TRANSFER_FAILURE ); _mint(msg.sender, _from, amount); emit Swap(msg.sender, _from, amount); } /**************************************************************************/ /************************** Holder information ****************************/ /** * @notice Retrieves the balance of a token holder for a specific partition. * @param _partition The partition for which the balance is returned. * @param _tokenHolder Address for which the balance is returned. * @return uint256 containing the amount of tokens held by `_tokenHolder` in `_partition`. */ function balanceOfByPartition(bytes32 _partition, address _tokenHolder) external view returns (uint256) { return _balanceOfByPartition[_tokenHolder][_partition]; } /** * @notice Retrieves the set of partitions for a particular token holder. * @param _tokenHolder Address for which the partitions are returned. * @return array containing the partitions of `_tokenHolder`. */ function partitionsOf(address _tokenHolder) external view returns (bytes32[] memory) { return _partitionsOf[_tokenHolder]; } /**************************************************************************/ /************************** Advanced Transfers ****************************/ /** * @notice Transfers tokens from a specific partition on behalf of a token * holder, optionally changing the partition and including * arbitrary data used by the partition strategies and collateral managers to authorize the * transfer. * @dev This can be used to transfer an address's own tokens, or transfer * a different address's tokens by specifying the `_from` param. If * attempting to transfer from a different address than `msg.sender`, the * `msg.sender` will need to be an operator or have enough allowance for the * `_partition` of the `_from` address. * @param _partition The partition from which the tokens are to be transferred. * @param _from Address from which the tokens are to be transferred. * @param _to Address to which the tokens are to be transferred. * @param _value Amount of tokens to be transferred. * @param _data Information attached to the transfer. Will contain the * destination partition if changing partitions. * @param _operatorData Additional data attached to the transfer. Used by partition strategies * and collateral managers to authorize the transfer. * @return bytes32 containing the destination partition. */ function transferByPartition( bytes32 _partition, address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external returns (bytes32) { return _transferByPartition( _partition, msg.sender, _from, _to, _value, _data, _operatorData ); } /**************************************************************************/ /************************** Operator Management ***************************/ /** * @notice Authorizes an address as an operator of `msg.sender` to transfer tokens on its * behalf. * @dev Note that this applies to all partitions. * * `msg.sender` is always an operator for itself, and does not need to * be explicitly added. * @param _operator Address to set as an operator for `msg.sender`. */ function authorizeOperator(address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperator[msg.sender][_operator] = true; emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Remove the right of the `_operator` address to be an operator for * `msg.sender` and to transfer tokens on its behalf. * @dev Note that this affects the account-wide authorization granted via function * `Amp.authorizeOperator`, and does not affect authorizations granted via function * `Amp.authorizeOperatorByPartition`. * * `msg.sender` is always an operator for itself, and cannot be * removed. * @param _operator Address to be deauthorized an operator for `msg.sender`. */ function revokeOperator(address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperator[msg.sender][_operator] = false; emit RevokedOperator(_operator, msg.sender); } /** * @notice Authorizes an account as an operator of a particular partition. * @dev The `msg.sender` is always an operator for itself, and does not need to * be explicitly added to a partition. * @param _partition The partition for which the `_operator` is to be authorized. * @param _operator Address to be authorized as an operator for `msg.sender`. */ function authorizeOperatorByPartition(bytes32 _partition, address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperatorByPartition[msg.sender][_partition][_operator] = true; emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender); } /** * @notice Deauthorizes an address as an operator for a particular partition. * @dev Note that this does not override an account-wide authorization granted via function * `Amp.authorizeOperator`. * * `msg.sender` is always an operator for itself, and cannot be * removed from a partition. * @param _partition The partition for which the `_operator` is deauthorized. * @param _operator Address to deauthorize as an operator for `msg.sender`. */ function revokeOperatorByPartition(bytes32 _partition, address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperatorByPartition[msg.sender][_partition][_operator] = false; emit RevokedOperatorByPartition(_partition, _operator, msg.sender); } /**************************************************************************/ /************************** Operator Information **************************/ /** * @notice Indicates whether the `_operator` address is an operator of the * `_tokenHolder` address. * @dev Note that this applies to all of the partitions of the `msg.sender` address. * @param _operator Address which may be an operator of `_tokenHolder`. * @param _tokenHolder Address of a token holder which may have the * `_operator` address as an operator. * @return bool indicating whether `_operator` is an operator of `_tokenHolder`. */ function isOperator(address _operator, address _tokenHolder) external view returns (bool) { return _isOperator(_operator, _tokenHolder); } /** * @notice Indicate whether the `_operator` address is an operator of the * `_tokenHolder` address for the `_partition`. * @param _partition Partition for which `_operator` may be authorized. * @param _operator Address which may be an operator of `_tokenHolder` for the `_partition`. * @param _tokenHolder Address of a token holder which may have the * `_operator` address as an operator for the `_partition`. * @return bool indicating whether `_operator` is an operator of `_tokenHolder` for the * `_partition`. */ function isOperatorForPartition( bytes32 _partition, address _operator, address _tokenHolder ) external view returns (bool) { return _isOperatorForPartition(_partition, _operator, _tokenHolder); } /** * @notice Indicates whether the `_operator` address is an operator of the * `_collateralManager` address for the `_partition`. * @dev This method is functionally identical to `Amp.isOperatorForPartition`, except that it * also requires the address that `_operator` is being checked for must be * a registered collateral manager. * @param _partition Partition for which the operator may be authorized. * @param _operator Address which may be an operator of `_collateralManager` * for the `_partition`. * @param _collateralManager Address of a collateral manager which may have * the `_operator` address as an operator for the `_partition`. * @return bool indicating whether the `_operator` address is an operator of the * `_collateralManager` address for the `_partition`. */ function isOperatorForCollateralManager( bytes32 _partition, address _operator, address _collateralManager ) external view returns (bool) { return _isCollateralManager[_collateralManager] && (_isOperator(_operator, _collateralManager) || _authorizedOperatorByPartition[_collateralManager][_partition][_operator]); } /**************************************************************************/ /***************************** Token metadata *****************************/ /** * @notice Retrieves the name of the token. * @return string containing the name of the token. Always "Amp". */ function name() external view returns (string memory) { return _name; } /** * @notice Retrieves the symbol of the token. * @return string containing the symbol of the token. Always "AMP". */ function symbol() external view returns (string memory) { return _symbol; } /** * @notice Retrieves the number of decimals of the token. * @return uint8 containing the number of decimals of the token. Always 18. */ function decimals() external pure returns (uint8) { return uint8(18); } /** * @notice Retrieves the smallest part of the token that is not divisible. * @return uint256 containing the smallest non-divisible part of the token. Always 1. */ function granularity() external pure returns (uint256) { return _granularity; } /** * @notice Retrieves the set of existing partitions. * @return array containing all partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /************************************************************************************************/ /******************************** Partition Token Allowances ************************************/ /** * @notice Retrieves the allowance of tokens that has been granted by a token holder to another * account. * @param _partition Partition for which the spender may be authorized. * @param _owner The address which owns the tokens. * @param _spender The address which is authorized transfer tokens on behalf of the token * holder. * @return uint256 containing the amount of tokens available for `_spender` to transfer. */ function allowanceByPartition( bytes32 _partition, address _owner, address _spender ) external view returns (uint256) { return _allowedByPartition[_partition][_owner][_spender]; } /** * @notice Approves the `_spender` address to transfer the specified amount of * tokens in `_partition` on behalf of `msg.sender`. * * Note that this method is subject to the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. Functions * `Amp.increaseAllowanceByPartition` and `Amp.decreaseAllowanceByPartition` should be used * instead. * @param _partition Partition for which the `_spender` is to be authorized to transfer tokens. * @param _spender The address of the account to be authorized to transfer tokens. * @param _value The amount of tokens to be authorized. * @return bool indicating if the operation was successful. */ function approveByPartition( bytes32 _partition, address _spender, uint256 _value ) external returns (bool) { _approveByPartition(_partition, msg.sender, _spender, _value); return true; } /** * @notice Increases the allowance granted to an account by the caller for a partition. * @dev This is an alternative to function `Amp.approveByPartition` that can be used as * a mitigation for the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * #### Requirements: * - `_spender` cannot be the zero address. * @param _partition Partition for which the `_spender` is to be authorized to transfer tokens. * @param _spender The address of the account to be authorized to transfer tokens. * @param _addedValue Additional amount of the `msg.sender`'s tokens `_spender` * is allowed to transfer. * @return bool indicating if the operation was successful. */ function increaseAllowanceByPartition( bytes32 _partition, address _spender, uint256 _addedValue ) external returns (bool) { _approveByPartition( _partition, msg.sender, _spender, _allowedByPartition[_partition][msg.sender][_spender].add(_addedValue) ); return true; } /** * @notice Decreases the allowance granted to `_spender` by the * caller. * @dev This is an alternative to function `Amp.approveByPartition` that can be used as * a mitigation for the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * #### Requirements: * - `_spender` cannot be the zero address. * - `_spender` must have allowance for the caller of at least * `_subtractedValue`. * @param _partition Partition for which `_spender`'s allowance is to be decreased. * @param _spender Amount by which the authorization for `_spender` to transfer tokens * held by `msg.sender`'s account is to be decreased. * @param _subtractedValue Amount of the `msg.sender`'s tokens `_spender` is * no longer allowed to transfer. * @return bool indicating if the operation was successful. */ function decreaseAllowanceByPartition( bytes32 _partition, address _spender, uint256 _subtractedValue ) external returns (bool) { _approveByPartition( _partition, msg.sender, _spender, _allowedByPartition[_partition][msg.sender][_spender].sub(_subtractedValue) ); return true; } /**************************************************************************/ /************************ Collateral Manager Admin ************************/ /** * @notice Registers `msg.sender` as a collateral manager. */ function registerCollateralManager() external { // Short circuit a double registry require(!_isCollateralManager[msg.sender], EC_5C_ADDRESS_CONFLICT); collateralManagers.push(msg.sender); _isCollateralManager[msg.sender] = true; emit CollateralManagerRegistered(msg.sender); } /** * @notice Retrieves whether the supplied address is a collateral manager. * @param _collateralManager The address of the collateral manager. * @return bool indicating whether `_collateralManager` is registered as a collateral manager. */ function isCollateralManager(address _collateralManager) external view returns (bool) { return _isCollateralManager[_collateralManager]; } /**************************************************************************/ /************************ Partition Strategy Admin ************************/ /** * @notice Sets an implementation for a partition strategy identified by `_prefix`. * @dev Note: this function can only be called by the contract owner. * @param _prefix The 4 byte partition prefix the strategy applies to. * @param _implementation The address of the implementation of the strategy hooks. */ function setPartitionStrategy(bytes4 _prefix, address _implementation) external { require(msg.sender == owner(), EC_56_INVALID_SENDER); require(!_isPartitionStrategy[_prefix], EC_5E_PARTITION_PREFIX_CONFLICT); require(_prefix != ZERO_PREFIX, EC_5F_INVALID_PARTITION_PREFIX_0); string memory iname = PartitionUtils._getPartitionStrategyValidatorIName(_prefix); ERC1820Client.setInterfaceImplementation(iname, _implementation); partitionStrategies.push(_prefix); _isPartitionStrategy[_prefix] = true; emit PartitionStrategySet(_prefix, iname, _implementation); } /** * @notice Return whether the `_prefix` has had a partition strategy registered. * @param _prefix The partition strategy identifier. * @return bool indicating if the strategy has been registered. */ function isPartitionStrategy(bytes4 _prefix) external view returns (bool) { return _isPartitionStrategy[_prefix]; } /**************************************************************************/ /*************************** INTERNAL FUNCTIONS ***************************/ /**************************************************************************/ /**************************************************************************/ /**************************** Token Transfers *****************************/ /** * @dev Transfer tokens from a specific partition. * @param _fromPartition Partition of the tokens to transfer. * @param _operator The address performing the transfer. * @param _from Token holder. * @param _to Token recipient. * @param _value Number of tokens to transfer. * @param _data Information attached to the transfer. Contains the destination * partition if a partition change is requested. * @param _operatorData Information attached to the transfer, by the operator * (if any). * @return bytes32 containing the destination partition. */ function _transferByPartition( bytes32 _fromPartition, address _operator, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData ) internal returns (bytes32) { require(_to != address(0), EC_57_INVALID_RECEIVER); // If the `_operator` is attempting to transfer from a different `_from` // address, first check that they have the requisite operator or // allowance permissions. if (_from != _operator) { require( _isOperatorForPartition(_fromPartition, _operator, _from) || (_value <= _allowedByPartition[_fromPartition][_from][_operator]), EC_53_INSUFFICIENT_ALLOWANCE ); // If the sender has an allowance for the partition, that should // be decremented if (_allowedByPartition[_fromPartition][_from][_operator] >= _value) { _allowedByPartition[_fromPartition][_from][msg .sender] = _allowedByPartition[_fromPartition][_from][_operator].sub( _value ); } else { _allowedByPartition[_fromPartition][_from][_operator] = 0; } } _callPreTransferHooks( _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); require( _balanceOfByPartition[_from][_fromPartition] >= _value, EC_52_INSUFFICIENT_BALANCE ); bytes32 toPartition = PartitionUtils._getDestinationPartition( _data, _fromPartition ); _removeTokenFromPartition(_from, _fromPartition, _value); _addTokenToPartition(_to, toPartition, _value); _callPostTransferHooks( toPartition, _operator, _from, _to, _value, _data, _operatorData ); emit Transfer(_from, _to, _value); emit TransferByPartition( _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); if (toPartition != _fromPartition) { emit ChangedPartition(_fromPartition, toPartition, _value); } return toPartition; } /** * @notice Transfer tokens from default partitions. * @dev Used as a helper method for ERC-20 compatibility. * @param _operator The address performing the transfer. * @param _from Token holder. * @param _to Token recipient. * @param _value Number of tokens to transfer. * @param _data Information attached to the transfer, and intended for the * token holder (`_from`). Should contain the destination partition if * changing partitions. */ function _transferByDefaultPartition( address _operator, address _from, address _to, uint256 _value, bytes memory _data ) internal { _transferByPartition(defaultPartition, _operator, _from, _to, _value, _data, ""); } /** * @dev Remove a token from a specific partition. * @param _from Token holder. * @param _partition Name of the partition. * @param _value Number of tokens to transfer. */ function _removeTokenFromPartition( address _from, bytes32 _partition, uint256 _value ) internal { if (_value == 0) { return; } _balances[_from] = _balances[_from].sub(_value); _balanceOfByPartition[_from][_partition] = _balanceOfByPartition[_from][_partition] .sub(_value); totalSupplyByPartition[_partition] = totalSupplyByPartition[_partition].sub( _value ); // If the total supply is zero, finds and deletes the partition. // Do not delete the _defaultPartition from totalPartitions. if (totalSupplyByPartition[_partition] == 0 && _partition != defaultPartition) { _removePartitionFromTotalPartitions(_partition); } // If the balance of the TokenHolder's partition is zero, finds and // deletes the partition. if (_balanceOfByPartition[_from][_partition] == 0) { uint256 index = _indexOfPartitionsOf[_from][_partition]; if (index == 0) { return; } // move the last item into the index being vacated bytes32 lastValue = _partitionsOf[_from][_partitionsOf[_from].length - 1]; _partitionsOf[_from][index - 1] = lastValue; // adjust for 1-based indexing _indexOfPartitionsOf[_from][lastValue] = index; _partitionsOf[_from].pop(); _indexOfPartitionsOf[_from][_partition] = 0; } } /** * @dev Add a token to a specific partition. * @param _to Token recipient. * @param _partition Name of the partition. * @param _value Number of tokens to transfer. */ function _addTokenToPartition( address _to, bytes32 _partition, uint256 _value ) internal { if (_value == 0) { return; } _balances[_to] = _balances[_to].add(_value); if (_indexOfPartitionsOf[_to][_partition] == 0) { _partitionsOf[_to].push(_partition); _indexOfPartitionsOf[_to][_partition] = _partitionsOf[_to].length; } _balanceOfByPartition[_to][_partition] = _balanceOfByPartition[_to][_partition] .add(_value); if (_indexOfTotalPartitions[_partition] == 0) { _addPartitionToTotalPartitions(_partition); } totalSupplyByPartition[_partition] = totalSupplyByPartition[_partition].add( _value ); } /** * @dev Add a partition to the total partitions collection. * @param _partition Name of the partition. */ function _addPartitionToTotalPartitions(bytes32 _partition) internal { _totalPartitions.push(_partition); _indexOfTotalPartitions[_partition] = _totalPartitions.length; } /** * @dev Remove a partition to the total partitions collection. * @param _partition Name of the partition. */ function _removePartitionFromTotalPartitions(bytes32 _partition) internal { uint256 index = _indexOfTotalPartitions[_partition]; if (index == 0) { return; } // move the last item into the index being vacated bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index; _totalPartitions.pop(); _indexOfTotalPartitions[_partition] = 0; } /**************************************************************************/ /********************************* Hooks **********************************/ /** * @notice Check for and call the `AmpTokensSender` hook on the sender address * (`_from`), and, if `_fromPartition` is within the scope of a strategy, * check for and call the `AmpPartitionStrategy.tokensFromPartitionToTransfer` * hook for the strategy. * @param _fromPartition Name of the partition to transfer tokens from. * @param _operator Address which triggered the balance decrease (through * transfer). * @param _from Token holder. * @param _to Token recipient for a transfer. * @param _value Number of tokens the token holder balance is decreased by. * @param _data Extra information, pertaining to the `_from` address. * @param _operatorData Extra information, attached by the operator (if any). */ function _callPreTransferHooks( bytes32 _fromPartition, address _operator, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(_from, AMP_TOKENS_SENDER); if (senderImplementation != address(0)) { IAmpTokensSender(senderImplementation).tokensToTransfer( msg.sig, _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); } // Used to ensure that hooks implemented by a collateral manager to validate // transfers from it's owned partitions are called bytes4 fromPartitionPrefix = PartitionUtils._getPartitionPrefix(_fromPartition); if (_isPartitionStrategy[fromPartitionPrefix]) { address fromPartitionValidatorImplementation; fromPartitionValidatorImplementation = interfaceAddr( address(this), PartitionUtils._getPartitionStrategyValidatorIName(fromPartitionPrefix) ); if (fromPartitionValidatorImplementation != address(0)) { IAmpPartitionStrategyValidator(fromPartitionValidatorImplementation) .tokensFromPartitionToValidate( msg.sig, _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); } } } /** * @dev Check for `AmpTokensRecipient` hook on the recipient and call it. * @param _toPartition Name of the partition the tokens were transferred to. * @param _operator Address which triggered the balance increase (through * transfer or mint). * @param _from Token holder for a transfer (0x when mint). * @param _to Token recipient. * @param _value Number of tokens the recipient balance is increased by. * @param _data Extra information related to the token holder (`_from`). * @param _operatorData Extra information attached by the operator (if any). */ function _callPostTransferHooks( bytes32 _toPartition, address _operator, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData ) internal { bytes4 toPartitionPrefix = PartitionUtils._getPartitionPrefix(_toPartition); if (_isPartitionStrategy[toPartitionPrefix]) { address partitionManagerImplementation; partitionManagerImplementation = interfaceAddr( address(this), PartitionUtils._getPartitionStrategyValidatorIName(toPartitionPrefix) ); if (partitionManagerImplementation != address(0)) { IAmpPartitionStrategyValidator(partitionManagerImplementation) .tokensToPartitionToValidate( msg.sig, _toPartition, _operator, _from, _to, _value, _data, _operatorData ); } } else { require(toPartitionPrefix == ZERO_PREFIX, EC_5D_PARTITION_RESERVED); } address recipientImplementation; recipientImplementation = interfaceAddr(_to, AMP_TOKENS_RECIPIENT); if (recipientImplementation != address(0)) { IAmpTokensRecipient(recipientImplementation).tokensReceived( msg.sig, _toPartition, _operator, _from, _to, _value, _data, _operatorData ); } } /**************************************************************************/ /******************************* Allowance ********************************/ /** * @notice Approve the `_spender` address to spend the specified amount of * tokens in `_partition` on behalf of `msg.sender`. * @param _partition Name of the partition. * @param _tokenHolder Owner of the tokens. * @param _spender The address which may spend the tokens. * @param _amount The amount of tokens available to be spent. */ function _approveByPartition( bytes32 _partition, address _tokenHolder, address _spender, uint256 _amount ) internal { require(_tokenHolder != address(0), EC_56_INVALID_SENDER); require(_spender != address(0), EC_58_INVALID_OPERATOR); _allowedByPartition[_partition][_tokenHolder][_spender] = _amount; emit ApprovalByPartition(_partition, _tokenHolder, _spender, _amount); if (_partition == defaultPartition) { emit Approval(_tokenHolder, _spender, _amount); } } /**************************************************************************/ /************************** Operator Information **************************/ /** * @dev Indicate whether the operator address is an operator of the * tokenHolder address. An operator in this case is an operator across all * partitions of the `msg.sender` address. * @param _operator Address which may be an operator of `_tokenHolder`. * @param _tokenHolder Address of a token holder which may have the `_operator` * address as an operator. * @return bool indicating whether `_operator` is an operator of `_tokenHolder` */ function _isOperator(address _operator, address _tokenHolder) internal view returns (bool) { return (_operator == _tokenHolder || _authorizedOperator[_tokenHolder][_operator]); } /** * @dev Indicate whether the operator address is an operator of the * tokenHolder address for the given partition. * @param _partition Name of the partition. * @param _operator Address which may be an operator of tokenHolder for the * `_partition`. * @param _tokenHolder Address of a token holder which may have the operator * address as an operator for the `_partition`. * @return bool indicating whether `_operator` is an operator of `_tokenHolder` for the * `_partition`. */ function _isOperatorForPartition( bytes32 _partition, address _operator, address _tokenHolder ) internal view returns (bool) { return (_isOperator(_operator, _tokenHolder) || _authorizedOperatorByPartition[_tokenHolder][_partition][_operator] || _callPartitionStrategyOperatorHook(_partition, _operator, _tokenHolder)); } /** * @notice Check if the `_partition` is within the scope of a strategy, and * call it's isOperatorForPartitionScope hook if so. * @dev This allows implicit granting of operatorByPartition permissions * based on the partition being used being of a strategy. * @param _partition The partition to check. * @param _operator The address to check if is an operator for `_tokenHolder`. * @param _tokenHolder The address to validate that `_operator` is an * operator for. */ function _callPartitionStrategyOperatorHook( bytes32 _partition, address _operator, address _tokenHolder ) internal view returns (bool) { bytes4 prefix = PartitionUtils._getPartitionPrefix(_partition); if (!_isPartitionStrategy[prefix]) { return false; } address strategyValidatorImplementation; strategyValidatorImplementation = interfaceAddr( address(this), PartitionUtils._getPartitionStrategyValidatorIName(prefix) ); if (strategyValidatorImplementation != address(0)) { return IAmpPartitionStrategyValidator(strategyValidatorImplementation) .isOperatorForPartitionScope(_partition, _operator, _tokenHolder); } // Not a partition format that imbues special operator rules return false; } /**************************************************************************/ /******************************** Minting *********************************/ /** * @notice Perform the minting of tokens. * @dev The tokens will be minted on behalf of the `_to` address, and will be * minted to the address's default partition. * @param _operator Address which triggered the issuance. * @param _to Token recipient. * @param _value Number of tokens issued. */ function _mint( address _operator, address _to, uint256 _value ) internal { require(_to != address(0), EC_57_INVALID_RECEIVER); _totalSupply = _totalSupply.add(_value); _addTokenToPartition(_to, defaultPartition, _value); _callPostTransferHooks( defaultPartition, _operator, address(0), _to, _value, "", "" ); emit Minted(_operator, _to, _value, ""); emit Transfer(address(0), _to, _value); emit TransferByPartition(bytes32(0), _operator, address(0), _to, _value, "", ""); } }
Remove a partition to the total partitions collection. _partition Name of the partition./
function _removePartitionFromTotalPartitions(bytes32 _partition) internal { uint256 index = _indexOfTotalPartitions[_partition]; if (index == 0) { return; } _indexOfTotalPartitions[lastValue] = index; _totalPartitions.pop(); _indexOfTotalPartitions[_partition] = 0; }
1,065,059
//Address: 0x904079be18b34fefea1307bc5e3c29ada6f201dc //Contract name: CrowdSale //Balance: 0 Ether //Verification Date: 3/2/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations that are safe for uint256 against overflow and negative values * @dev https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ 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; } } /** * @title Moderated * @dev restricts execution of 'onlyModerator' modified functions to the contract moderator * @dev restricts execution of 'ifUnrestricted' modified functions to when unrestricted * boolean state is true * @dev allows for the extraction of ether or other ERC20 tokens mistakenly sent to this address */ contract Moderated { address public moderator; bool public unrestricted; modifier onlyModerator { require(msg.sender == moderator); _; } modifier ifUnrestricted { require(unrestricted); _; } modifier onlyPayloadSize(uint256 numWords) { assert(msg.data.length >= numWords * 32 + 4); _; } function Moderated() public { moderator = msg.sender; unrestricted = true; } function reassignModerator(address newModerator) public onlyModerator { moderator = newModerator; } function restrict() public onlyModerator { unrestricted = false; } function unrestrict() public onlyModerator { unrestricted = true; } /// This method can be used to extract tokens mistakenly sent to this contract. /// @param _token The address of the token contract that you want to recover function extract(address _token) public returns (bool) { require(_token != address(0x0)); Token token = Token(_token); uint256 balance = token.balanceOf(this); return token.transfer(moderator, balance); } function isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return (size > 0); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract Token { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Controlled * @dev Restricts execution of modified functions to the contract controller alone */ contract Controlled { address public controller; function Controlled() public { controller = msg.sender; } modifier onlyController { require(msg.sender == controller); _; } function transferControl(address newController) public onlyController{ controller = newController; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Controlled { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function () external payable { revert(); } function deposit(address investor) onlyController public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyController public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyController public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract CrowdSale is Moderated { using SafeMath for uint256; // LEON ERC20 smart contract Token public tokenContract; // crowdsale starts 1 March 2018, 00h00 PDT uint256 public constant startDate = 1519891200; // crowdsale ends 31 December 2018, 23h59 PDT uint256 public constant endDate = 1546243140; // crowdsale aims to sell at least 100 000 LEONS uint256 public constant crowdsaleTarget = 100000 * 10**18; uint256 public constant margin = 1000 * 10**18; // running total of tokens sold uint256 public tokensSold; // ethereum to US Dollar exchange rate uint256 public etherToUSDRate; // address to receive accumulated ether given a successful crowdsale address public constant etherVault = 0xD8d97E3B5dB13891e082F00ED3fe9A0BC6B7eA01; // vault contract escrows ether and facilitates refunds given unsuccesful crowdsale RefundVault public refundVault; // minimum of 0.005 ether to participate in crowdsale uint256 constant purchaseThreshold = 5 finney; // boolean to indicate crowdsale finalized state bool public isFinalized = false; bool public active = false; // finalization event event Finalized(); // purchase event event Purchased(address indexed purchaser, uint256 indexed tokens); // checks that crowd sale is live modifier onlyWhileActive { require(now >= startDate && now <= endDate && active); _; } function CrowdSale(address _tokenAddr, uint256 price) public { // the LEON token contract tokenContract = Token(_tokenAddr); // initiate new refund vault to escrow ether from purchasers refundVault = new RefundVault(etherVault); etherToUSDRate = price; } function setRate(uint256 _rate) public onlyModerator returns (bool) { etherToUSDRate = _rate; } // fallback function invokes buyTokens method function() external payable { buyTokens(msg.sender); } // forwards ether received to refund vault and generates tokens for purchaser function buyTokens(address _purchaser) public payable ifUnrestricted onlyWhileActive returns (bool) { require(!targetReached()); require(msg.value > purchaseThreshold); refundVault.deposit.value(msg.value)(_purchaser); // 1 LEON is priced at 1 USD // etherToUSDRate is stored in cents, /100 to get USD quantity // crowdsale offers 100% bonus, purchaser receives (tokens before bonus) * 2 // tokens = (ether * etherToUSDRate in cents) * 2 / 100 uint256 _tokens = (msg.value).mul(etherToUSDRate).div(50); require(tokenContract.transferFrom(moderator,_purchaser, _tokens)); tokensSold = tokensSold.add(_tokens); Purchased(_purchaser, _tokens); return true; } function initialize() public onlyModerator returns (bool) { require(!active && !isFinalized); require(tokenContract.allowance(moderator,address(this)) == crowdsaleTarget + margin); active = true; } // activates end of crowdsale state function finalize() public onlyModerator { // cannot have been invoked before require(!isFinalized); // can only be invoked after end date or if target has been reached require(hasEnded() || targetReached()); // if crowdsale has been successful if(targetReached()) { // close refund vault and forward ether to etherVault refundVault.close(); // if the sale was unsuccessful } else { // activate refund vault refundVault.enableRefunds(); } // emit Finalized event Finalized(); // set isFinalized boolean to true isFinalized = true; active = false; } // checks if end date of crowdsale is passed function hasEnded() internal view returns (bool) { return (now > endDate); } // checks if crowdsale target is reached function targetReached() internal view returns (bool) { return (tokensSold >= crowdsaleTarget); } // refunds ether to investors if crowdsale is unsuccessful function claimRefund() public { // can only be invoked after sale is finalized require(isFinalized); // can only be invoked if sale target was not reached require(!targetReached()); // if msg.sender invested ether during crowdsale - refund them of their contribution refundVault.refund(msg.sender); } }
forwards ether received to refund vault and generates tokens for purchaser 1 LEON is priced at 1 USD etherToUSDRate is stored in cents, /100 to get USD quantity crowdsale offers 100% bonus, purchaser receives (tokens before bonus) 2 tokens = (ether etherToUSDRate in cents) 2 / 100
function buyTokens(address _purchaser) public payable ifUnrestricted onlyWhileActive returns (bool) { require(!targetReached()); require(msg.value > purchaseThreshold); refundVault.deposit.value(msg.value)(_purchaser); uint256 _tokens = (msg.value).mul(etherToUSDRate).div(50); require(tokenContract.transferFrom(moderator,_purchaser, _tokens)); tokensSold = tokensSold.add(_tokens); Purchased(_purchaser, _tokens); return true; }
12,559,059
./partial_match/1/0xF322F55E44257d0d8F5E4bde706Ec8cdF9772f2e/sources/TokenFactory.sol
Mint. _account Address to mint tokens to. _amount Amount to mint./
function mint(address _account, uint256 _amount) public { if(isSystem(msg.sender)){ require(!isFrozen(_account), "SygnumToken: Account must not be frozen if system calling."); } super._mint(_account, _amount); emit Minted(msg.sender, _account, _amount); }
4,224,597
// Sources flattened with hardhat v2.8.2 https://hardhat.org // File contracts/lib/LibAppStorage.sol /** * SPDX-License-Identifier: MIT * * Copyright (c) 2021 YellowHeart * * 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 * 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. */ pragma solidity 0.8.9; enum AuthorizationState { Unused, Used, Canceled } struct AppStorage { address owner; address pauser; bool paused; address blacklister; mapping(address => bool) blacklisted; string name; string symbol; uint8 decimals; string currency; address masterMinter; bool initialized; bool initializing; bool initializedV2; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; uint256 totalSupply; mapping(address => bool) minters; mapping(address => uint256) minterAllowed; address rescuer; bytes32 domainSeparator; mapping(address => mapping(bytes32 => AuthorizationState)) authorizationStates; mapping(address => uint256) nonces; } library LibAppStorage { function diamondStorage() internal pure returns (AppStorage storage ds) { assembly { ds.slot := 0 } } } // File @openzeppelin/contracts/utils/math/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // 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; } } } // File @openzeppelin/contracts/token/ERC20/[email protected] // // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) /** * @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 contracts/lib/LibContext.sol /** * * * Copyright (c) YellowHeart * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibContext { function _msgSender() internal view returns (address 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/lib/LibOwnable.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ library LibOwnable { function _requireOnlyOwner() internal view { require( LibContext._msgSender() == LibAppStorage.diamondStorage().owner, "Ownable: caller is not the owner" ); } } // File contracts/common/Ownable.sol /** * * * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return LibAppStorage.diamondStorage().owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { LibAppStorage.diamondStorage().owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { LibOwnable._requireOnlyOwner(); _; } /** * @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) external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(LibAppStorage.diamondStorage().owner, newOwner); setOwner(newOwner); } } // File contracts/lib/LibBlacklistable.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ library LibBlacklistable { function _requireBlacklister() internal view { require( msg.sender == LibAppStorage.diamondStorage().blacklister, "Blacklistable: caller is not the blacklister" ); } function _requireNotBlacklisted(address account) internal view { require( !LibAppStorage.diamondStorage().blacklisted[account], "Blacklistable: account is blacklisted" ); } } // File contracts/common/Blacklistable.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { event Blacklisted(address indexed account); event UnBlacklisted(address indexed account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { LibBlacklistable._requireBlacklister(); _; } /** * @dev Throws if argument account is blacklisted * @param account The address to check */ modifier notBlacklisted(address account) { LibBlacklistable._requireNotBlacklisted(account); _; } function blacklister() external view returns (address) { return LibAppStorage.diamondStorage().blacklister; } /** * @dev Checks if account is blacklisted * @param account The address to check */ function isBlacklisted(address account) external view returns (bool) { return LibAppStorage.diamondStorage().blacklisted[account]; } /** * @dev Adds account to blacklist * @param account The address to blacklist */ function blacklist(address account) external onlyBlacklister { LibAppStorage.diamondStorage().blacklisted[account] = true; emit Blacklisted(account); } /** * @dev Removes account from blacklist * @param account The address to remove from the blacklist */ function unBlacklist(address account) external onlyBlacklister { LibAppStorage.diamondStorage().blacklisted[account] = false; emit UnBlacklisted(account); } function updateBlacklister(address newBlacklister) external onlyOwner { require(newBlacklister != address(0), "Blacklistable: new blacklister is the zero address"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); appStorage.blacklister = newBlacklister; emit BlacklisterChanged(appStorage.blacklister); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/introspection/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 @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) /** * @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); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol) // File contracts/lib/LibERC20.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibERC20 { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Internal function to set allowance * @param owner_ Token owner's address * @param spender Spender's address * @param value Allowance amount */ function _approve( address owner_, address spender, uint256 value ) internal { require(owner_ != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); appStorage.allowed[owner_][spender] = value; emit Approval(owner_, spender, value); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal { AppStorage storage appStorage = LibAppStorage.diamondStorage(); uint256 currentAllowance = appStorage.allowed[owner][spender]; _approve(owner, spender, currentAllowance.add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal { AppStorage storage appStorage = LibAppStorage.diamondStorage(); _approve( owner, spender, appStorage.allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); require(value <= appStorage.balances[from], "ERC20: transfer amount exceeds balance"); appStorage.balances[from] = appStorage.balances[from].sub(value); appStorage.balances[to] = appStorage.balances[to].add(value); emit Transfer(from, to, value); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function _transferFrom( address from, address to, uint256 value ) internal returns (bool) { _transfer(from, to, value); AppStorage storage appStorage = LibAppStorage.diamondStorage(); address msgSender = LibContext._msgSender(); uint256 currentAllowance = appStorage.allowed[from][msgSender]; require(value <= currentAllowance, "ERC20: transfer amount exceeds allowance"); appStorage.allowed[from][msgSender] = currentAllowance.sub(value); return true; } } // File contracts/lib/LibPausable.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ library LibPausable { function _requireNotPaused() internal view { require(!LibAppStorage.diamondStorage().paused, "Pausable: paused"); } function _requireOnlyPauser() internal view { require( LibContext._msgSender() == LibAppStorage.diamondStorage().pauser, "Pausable: caller is not the pauser" ); } } // File contracts/common/Pausable.sol /** * * * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * 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 * 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. */ /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { LibPausable._requireNotPaused(); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { LibPausable._requireOnlyPauser(); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { LibAppStorage.diamondStorage().paused = true; emit Pause(); } function paused() external view returns (bool) { return LibAppStorage.diamondStorage().paused; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { LibAppStorage.diamondStorage().paused = false; emit Unpause(); } function pauser() external view returns (address) { return LibAppStorage.diamondStorage().pauser; } /** * @dev update the pauser role */ function updatePauser(address newPauser) external onlyOwner { require(newPauser != address(0), "Pausable: new pauser is the zero address"); LibAppStorage.diamondStorage().pauser = newPauser; emit PauserChanged(LibAppStorage.diamondStorage().pauser); } } // File @openzeppelin/contracts/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @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); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.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 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"); } } } // File contracts/common/Rescuable.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ contract Rescuable is Ownable { using SafeERC20 for IERC20; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return LibAppStorage.diamondStorage().rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { _requireOnlyRescuer(); _; } function _requireOnlyRescuer() internal view { require( msg.sender == LibAppStorage.diamondStorage().rescuer, "Rescuable: caller is not the rescuer" ); } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require(newRescuer != address(0), "Rescuable: new rescuer is the zero address"); LibAppStorage.diamondStorage().rescuer = newRescuer; emit RescuerChanged(newRescuer); } } // File @openzeppelin/contracts/proxy/beacon/[email protected] // // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts/proxy/ERC1967/[email protected] // // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @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 Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot( _ROLLBACK_SLOT ); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require( oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades" ); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @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 Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // File @openzeppelin/contracts/proxy/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol) /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; } // File contracts/common/BaseToken.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ /** * @title BaseToken */ abstract contract BaseToken is UUPSUpgradeable, IERC165, IERC20, IERC20Metadata, Ownable, Pausable, Blacklistable, Rescuable { using SafeMath for uint256; AppStorage internal appStorage; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function _msgSender() internal view virtual returns (address) { return LibContext._msgSender(); } /** * @dev Authorizes the contract owner to perform a contract upgrade. */ function _authorizeUpgrade(address) internal virtual override onlyOwner { this; } function implementation() external view returns (address) { return _getImplementation(); } function name() external view returns (string memory) { return appStorage.name; } function symbol() external view returns (string memory) { return appStorage.symbol; } function decimals() external view returns (uint8) { return appStorage.decimals; } /** * @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) public view virtual override returns (bool) { return interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Metadata).interfaceId || interfaceId == type(IERC165).interfaceId; } /** * @dev Internal function to mint tokens. * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function _mint(address to, uint256 amount) internal returns (bool) { address msgSender = _msgSender(); appStorage.totalSupply = appStorage.totalSupply.add(amount); appStorage.balances[to] = appStorage.balances[to].add(amount); emit Mint(msgSender, to, amount); emit Transfer(address(0), to, amount); return true; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param tokenOwner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address tokenOwner, address spender) external view override returns (uint256) { return appStorage.allowed[tokenOwner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external view override returns (uint256) { return appStorage.totalSupply; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external view override returns (uint256) { return appStorage.balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(_msgSender()) notBlacklisted(spender) returns (bool) { LibERC20._approve(_msgSender(), spender, value); return true; } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(_msgSender()) notBlacklisted(from) notBlacklisted(to) returns (bool) { return LibERC20._transferFrom(from, to, value); } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(_msgSender()) notBlacklisted(to) returns (bool) { LibERC20._transfer(_msgSender(), to, value); return true; } /** * @dev allows a user to burn some of its own tokens * Validates that amount is less than or equal to the caller's account balance * @param amount uint256 the amount of tokens to be burned */ function _burn(uint256 amount) internal virtual { address msgSender = _msgSender(); uint256 balance = appStorage.balances[msgSender]; require(amount > 0, "BaseToken: burn amount not greater than 0"); require(balance >= amount, "BaseToken: burn amount exceeds balance"); appStorage.totalSupply = appStorage.totalSupply.sub(amount); appStorage.balances[msgSender] = balance.sub(amount); } } // File contracts/lib/LibECRecover.sol /** * * * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // 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("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } // File contracts/lib/LibEIP712.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library LibEIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, // = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, keccak256(typeHashAndData)) ); return LibECRecover.recover(digest, v, r, s); } } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363.sol) interface IERC1363 is IERC165, IERC20 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool); /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value ) external returns (bool); /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value, bytes memory data ) external returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall( address spender, uint256 value, bytes memory data ) external returns (bool); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Receiver.sol) interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived( address operator, address from, uint256 value, bytes memory data ) external returns (bytes4); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Spender.sol) interface IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived( address owner, uint256 value, bytes memory data ) external returns (bytes4); } // File contracts/lib/LibERC1363.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibERC1363 { using Address for address; using SafeMath for uint256; /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 private constant INTERFACE_TRANSFER_AND_CALL = 0x4bbee2df; /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 private constant INTERFACE_APPROVE_AND_CALL = 0xfb9ec8ce; function _supportsInterface(bytes4 interfaceId) internal pure returns (bool) { return interfaceId == INTERFACE_TRANSFER_AND_CALL || interfaceId == INTERFACE_APPROVE_AND_CALL || interfaceId == type(IERC1363).interfaceId; } /** * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function _transferAndCall( address to, uint256 value, bytes memory data ) internal returns (bool) { address msgSender = LibContext._msgSender(); LibERC20._transfer(msgSender, to, value); require( _checkAndCallTransfer(msgSender, to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; } /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function _transferFromAndCall( address from, address to, uint256 value, bytes memory data ) internal returns (bool) { LibERC20._transferFrom(from, to, value); require( _checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; } /** * @dev Internal function to invoke `onTransferReceived` on a target address * The call is not executed if the target address is not a contract * @param sender address Representing the previous owner of the given token value * @param recipient address Target address that will receive the tokens * @param amount uint256 The amount mount of tokens to be transferred * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallTransfer( address sender, address recipient, uint256 amount, bytes memory data ) internal returns (bool) { if (!recipient.isContract()) { return false; } bytes4 retval = IERC1363Receiver(recipient).onTransferReceived( LibContext._msgSender(), sender, amount, data ); return (retval == IERC1363Receiver(recipient).onTransferReceived.selector); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function _approveAndCall( address spender, uint256 value, bytes memory data ) internal returns (bool) { LibERC20._approve(LibContext._msgSender(), spender, value); require( _checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts" ); return true; } /** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param amount uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallApprove( address spender, uint256 amount, bytes memory data ) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( LibContext._msgSender(), amount, data ); return (retval == IERC1363Spender(spender).onApprovalReceived.selector); } } // File contracts/common/ERC1363.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ abstract contract ERC1363 is IERC1363, Pausable, Blacklistable { /** * @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) public view virtual override returns (bool) { return LibERC1363._supportsInterface(interfaceId); } /** * @dev Transfer tokens from `msgSender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(to) returns (bool) { return LibERC1363._transferAndCall(to, value, ""); } /** * @dev Transfer tokens from `msgSender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall( address to, uint256 value, bytes memory data ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(to) returns (bool) { return LibERC1363._transferAndCall(to, value, data); } /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(from) notBlacklisted(to) returns (bool) { return LibERC1363._transferFromAndCall(from, to, value, ""); } /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value, bytes memory data ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(from) notBlacklisted(to) returns (bool) { return LibERC1363._transferFromAndCall(from, to, value, data); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msgSender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(spender) returns (bool) { return LibERC1363._approveAndCall(spender, value, ""); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msgSender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall( address spender, uint256 value, bytes memory data ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(spender) returns (bool) { return LibERC1363._approveAndCall(spender, value, data); } } // File contracts/lib/LibGasAbstraction.sol // // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ApproveWithAuthorization(address owner,address spender,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _APPROVE_WITH_AUTHORIZATION_TYPEHASH = 0x808c10407a796f3ef2c7ea38c0638ea9d2b8a1c63e3ca9e1f56ce84ae59df73c; // keccak256("IncreaseAllowanceWithAuthorization(address owner,address spender,uint256 increment,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0x424222bb050a1f7f14017232a5671f2680a2d3420f504bd565cf03035c53198a; // keccak256("DecreaseAllowanceWithAuthorization(address owner,address spender,uint256 decrement,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0xb70559e94cbda91958ebec07f9b65b3b490097c8d25c8dacd71105df1015b6d8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 constant _CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @title Gas Abstraction * @notice Provide internal implementation for gas-abstracted transfers and * approvals * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ library LibGasAbstraction { event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce); /** * @notice Verify a signed transfer authorization and execute if valid * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( _TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == from, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(from, nonce); LibERC20._transfer(from, to, value); } /** * @notice Verify a signed authorization for an increase in the allowance * granted to the spender and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param increment Amount of increase in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, increment, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == owner, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); LibERC20._increaseAllowance(owner, spender, increment); } /** * @notice Verify a signed authorization for a decrease in the allowance * granted to the spender and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param decrement Amount of decrease in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _decreaseAllowanceWithAuthorization( address owner, address spender, uint256 decrement, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, decrement, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == owner, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); LibERC20._decreaseAllowance(owner, spender, decrement); } /** * @notice Verify a signed approval authorization and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _approveWithAuthorization( address owner, address spender, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( _APPROVE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, value, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == owner, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); LibERC20._approve(owner, spender, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode(_CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == authorizer, "GasAbstraction: invalid signature" ); LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] = AuthorizationState .Canceled; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] == AuthorizationState.Unused, "GasAbstraction: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require(block.timestamp > validAfter, "GasAbstraction: authorization is not yet valid"); require(block.timestamp < validBefore, "GasAbstraction: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] = AuthorizationState .Used; emit AuthorizationUsed(authorizer, nonce); } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= block.timestamp, "Permit: permit is expired"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); bytes memory data = abi.encode( _PERMIT_TYPEHASH, owner, spender, value, appStorage.nonces[owner]++, deadline ); require( LibEIP712.recover(appStorage.domainSeparator, v, r, s, data) == owner, "Permit: invalid signature" ); LibERC20._approve(owner, spender, value); } } // File contracts/common/EIP712Domain.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ // solhint-disable-next-line function DOMAIN_SEPARATOR() external view returns (bytes32) { return LibAppStorage.diamondStorage().domainSeparator; } } // File contracts/common/GasAbstraction.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title Gas Abstraction * @notice Provide internal implementation for gas-abstracted transfers and * approvals * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract GasAbstraction is EIP712Domain { bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = _TRANSFER_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant APPROVE_WITH_AUTHORIZATION_TYPEHASH = _APPROVE_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = _CANCEL_AUTHORIZATION_TYPEHASH; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce); /** * @notice Returns the state of an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return Authorization state */ function authorizationState(address authorizer, bytes32 nonce) external view returns (AuthorizationState) { return LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce]; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external returns (bool) { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(msg.sender); LibBlacklistable._requireNotBlacklisted(spender); LibERC20._increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external returns (bool) { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(msg.sender); LibBlacklistable._requireNotBlacklisted(spender); LibERC20._decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(from); LibBlacklistable._requireNotBlacklisted(to); LibGasAbstraction._transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Update allowance with a signed authorization * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function approveWithAuthorization( address tokenOwner, address spender, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._approveWithAuthorization( tokenOwner, spender, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Increase allowance with a signed authorization * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param increment Amount of increase in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function increaseAllowanceWithAuthorization( address tokenOwner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._increaseAllowanceWithAuthorization( tokenOwner, spender, increment, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Decrease allowance with a signed authorization * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param decrement Amount of decrease in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function decreaseAllowanceWithAuthorization( address tokenOwner, address spender, uint256 decrement, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._decreaseAllowanceWithAuthorization( tokenOwner, spender, decrement, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibGasAbstraction._cancelAuthorization(authorizer, nonce, v, r, s); } } // File contracts/common/Permit.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title Permit * @notice An alternative to approveWithAuthorization, provided for * compatibility with the draft EIP2612 proposed by Uniswap. * @dev Differences: * - Uses sequential nonce, which restricts transaction submission to one at a * time, or else it will revert * - Has deadline (= validBefore - 1) but does not have validAfter * - Doesn't have a way to change allowance atomically to prevent ERC20 multiple * withdrawal attacks */ abstract contract Permit is EIP712Domain { bytes32 public constant PERMIT_TYPEHASH = _PERMIT_TYPEHASH; /** * @notice Nonces for permit (shared with meta transaction) * @dev Nonces is shared for permits and meta transaction nonces. The nonces and getNonce * methods both return the same nonce sequence, but are both kept for compatability * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return LibAppStorage.diamondStorage().nonces[owner]; } /** * @notice Update allowance with a signed permit * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address tokenOwner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._permit(tokenOwner, spender, value, deadline, v, r, s); } } // File contracts/tokens/HeartToken.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ contract HeartToken is BaseToken, GasAbstraction, Permit, ERC1363 { using SafeMath for uint256; uint256 public constant MAX_SUPPLY = 692000000 * 1e18; function initialize( string memory tokenName, string memory tokenSymbol, address newPauser, address newBlacklister, address newOwner, address tokenReceiver ) external { require(!appStorage.initialized, "HeartToken: contract is already initialized"); require(newPauser != address(0), "HeartToken: new pauser is the zero address"); require(newBlacklister != address(0), "HeartToken: new blacklister is the zero address"); require(newOwner != address(0), "HeartToken: new owner is the zero address"); require(tokenReceiver != address(0), "HeartToken: token receiver is the zero address"); appStorage.name = tokenName; appStorage.symbol = tokenSymbol; appStorage.decimals = 18; // appStorage.masterMinter = newMasterMinter; appStorage.pauser = newPauser; appStorage.blacklister = newBlacklister; setOwner(newOwner); appStorage.domainSeparator = LibEIP712.makeDomainSeparator(tokenName, "1"); _mint(tokenReceiver, MAX_SUPPLY); require( appStorage.totalSupply == MAX_SUPPLY, "HeartToken: totalSupply is not expected value" ); require( appStorage.balances[tokenReceiver] == MAX_SUPPLY, "HeartToken: tokenReceiver balance is not expected value" ); appStorage.initialized = true; } /** * @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) public view virtual override(BaseToken, ERC1363) returns (bool) { return ERC1363.supportsInterface(interfaceId) || BaseToken.supportsInterface(interfaceId); } }
Internal function to invoke `onApprovalReceived` on a target address The call is not executed if the target address is not a contract spender address The address which will spend the funds amount uint256 The amount of tokens to be spent data bytes Optional data to send along with the call return whether the call correctly returned the expected magic value/
function _checkAndCallApprove( address spender, uint256 amount, bytes memory data ) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( LibContext._msgSender(), amount, data ); return (retval == IERC1363Spender(spender).onApprovalReceived.selector); }
6,926,082
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // @title: Crypto Panther Club // @developer: Arthur V. // @artist: https://marcinglod.com // @url: https://cryptopanther.club // // ,,,. // ,(%&&&&/ ,@@@#//&@@#. // (@&@# .* .&@@&&@@% (@% &@@.#@&@. // #@&@,/@@@( .#@@@@@@#, #@@@@@@@@&@( #@*,%*,%@@@( // &@&@* /%* *@@@@&#(/,. *@@@. .,,*/* * &@@@@@@@@@&&&%@@@&/ // .*#%(,*. *(#%@%*./@(,@&@#.&@@@@@@&&&./@&&&&&&&&&&&&@* // ,@@&@./@@@@@&* *.,@&&@# ,#&&%, /@&&&&&&&&&&&&&&@% // ,@&&@@&( .*/#&@@& /@&&&&&&@@&&&@&&&&@&&&&&&&&&&&&@& // #@* *@@@@@@@@@# %@&&&&&&&@@&&&&&@@*[email protected]&&&&&&&&&&&@* // .* .,*(&@&&&&&#,.***,./&@&&&&&&&&&&@( // *. /@@@@( ,@&&&&&@/ @@&&&&&&&&&&&@&. // %@@#. .#@@@@@@@@% (@@&*.#@&&&&&&&&&@@#, // %@@@@@@( #@@@@@@@@@@@@# .%@&&&@@@@@@@@( // (/(&@@@@@.*@@@@@@@@@@&##&* &&&&&&/,#%#%* // (@@@@@@@/*@@@@@@@@@@@&@& (%#((, *,.,,/&# // .,,(#, ,**/((#(//.*&@&&@/ #@&&@@@% // %@@@@@@@@@@* *@@@( %@&@* *@&&&&@* // ,**, /%@@@@&* /@@&&&&@.,@&, .&@&&@& // %@&&&@@% * *@@&&&&&&@/ @% &@&&@# ,&@@&%/. // (@@&&@&*.#@&&&&&&&@# #&, .&@&@/.&@&&&&&&&@@&%(*. // %@ @@&&&&&&@@/ .* (@&&&&&&&&&&&&&&&&&&&&@@&(. // %@&&&&&&/,/%&@@@@%. #@&&@&#(%&@&&&&&&&&&&&&&&&&&&&@@&#*. // /@&&&&&%%@&&&&@@@%%* *@&@( /@@@( %@&&&##&@@@@&&&&&&&&&&&&@@% // &@&&&&&&&&&#*/#%&&@#. /@@,[email protected]@@@@@@@* %@&&&&/ .*(%&@&&&&&&&& // %@&&&&&&&@@&&&&&&&&@/ /@( @@@@@@@@@@@ *@&&&@# *&@@&&& // /@&&&&&&&&@%(@@&&&@% *@*[email protected]@@@@@@@@@@@.,@&&&@% ,/% // &@&&&&&&&&@/ #@@@, ,@*[email protected]@@@@@@@@@@@@, @&&&&@, // /@&&&&&&&&&@%, [email protected]( @@@@@@@@@@@@@@/ &@&&&@/ // &@&&&&&&&&&@* &@ (@@@@@@@@@@@@@@# %@&&&@% // (@&&&&&&@#. %@/ @@@@@@@@@@@@@@@&.*@&&&&@* // ,@&&&@# #@@ /@@@@@@@@@@@@@@@@/ &@&&&@& // .&@&&@&, #@@% %@@@@@@@@@@@@@@@@&./@&&&&@# // (@&&&@@. (@&@( &@@@@@@@@@@@@@@@@@# &@&&&&@( // ,@&&&&@&* /@&&@/ &@@@@@@@@@@@@@@@@@@*,&&&&&&@( import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract CryptoPantherClub is ERC721, ReentrancyGuard, VRFConsumerBase, Ownable { // ======== Counter ========= using Counters for Counters.Counter; Counters.Counter private supplyCounter; // ======== Supply ========= uint256 public constant MAX_SUPPLY = 5555; // ======== Max Mints Per Address ========= uint256 public maxPerAddressWhitelist; uint256 public maxPerAddressPublic; // ======== Price ========= uint256 public priceWhitelist; uint256 public pricePublic; // ======== Mints Per Address Mapping ======== struct MintTypes { uint256 _numberOfMintsByAddress; } mapping(address => MintTypes) public addressToMints; // ======== Base URI ========= string private baseURI; // ======== Phase ========= enum SalePhase{ Locked, Whitelist, PrePublic, Public, Ended } SalePhase public phase = SalePhase.Locked; // ======== Chainlink VRF (v.1) ======== bytes32 internal immutable keyHash; uint256 internal immutable fee; uint256 public indexShift = 0; // ======== Whitelist Coupons ======== address private constant ownerSigner = 0x493e23ed0756415107993FE3D777Ca1A356FB038; enum CouponType{ Whitelist } struct Coupon { bytes32 r; bytes32 s; uint8 v; } // ======== Constructor ========= constructor( string memory name_, string memory symbol_, string memory hiddenURI_ ) VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) ERC721(name_, symbol_) { baseURI = hiddenURI_; keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; // VRF keyHash fee = 2 * 10 ** 18; // 2 LINK } // ======== Team Reserve (Events, Promotions, etc.) ========= function reserve(uint256 amount_) external onlyLockedPhase onlyOwner { require(amount_ > 0, "Amount can't be zero."); for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } } // ======== Set Whitelist Price ======== function setPriceWhitelist(uint256 price_) external onlyLockedPhase onlyOwner { priceWhitelist = price_; } // ======== Set Public Pirce ======== function setPricePublic(uint256 price_) external onlyPrePublicPhase onlyOwner { pricePublic = price_; } // ======== Set Max Whitelist Mint Amount Per Address ======== function setMaxPerAddressWhitelist(uint256 amount_) external onlyLockedPhase onlyOwner { maxPerAddressWhitelist = amount_; } // ======== Set Max Public Mint Amount Per Address ======== function setMaxPerAddressPublic(uint256 amount_) external onlyPrePublicPhase onlyOwner { maxPerAddressPublic = amount_; } // ======== Enable Whitelist Mint ========= function setWhitelistPhase() external onlyLockedPhase onlyOwner { require(priceWhitelist != 0, "Whitelist price is not set."); require(maxPerAddressWhitelist != 0, "Max whitelist mint amount not set."); phase = SalePhase.Whitelist; } // ======== Enable PrePublic Phase ========= function setPrePublicPhase() external onlyWhitelistPhase onlyOwner { phase = SalePhase.PrePublic; } // ======== Enable Public Mint ========= function setPublicPhase() external onlyPrePublicPhase onlyOwner { require(pricePublic != 0, "Public price is not set."); require(maxPerAddressPublic != 0, "Max public mint amount not set."); phase = SalePhase.Public; } // ======== End Sale ========= function setEndedPhase() external onlyOwner { phase = SalePhase.Ended; } // ======== Whitelist Mint ========= function whitelistMint(uint256 amount_, Coupon memory coupon_) public payable onlyWhitelistPhase validateAmount(amount_, maxPerAddressWhitelist) validateSupply(amount_) validateEthPayment(amount_, priceWhitelist) nonReentrant { require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressWhitelist, "Exceeds number of whitelist mints allowed."); bytes32 digest = keccak256(abi.encode(CouponType.Whitelist, msg.sender)); require(isVerifiedCoupon(digest, coupon_), "Invalid coupon"); addressToMints[msg.sender]._numberOfMintsByAddress += amount_; for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } if (totalSupply() == MAX_SUPPLY) { phase = SalePhase.Ended; } } // ======== Public Mint ========= function mint(uint256 amount_) public payable onlyPublicPhase validateAmount(amount_, maxPerAddressPublic) validateSupply(amount_) validateEthPayment(amount_, pricePublic) nonReentrant { require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressPublic, "Exceeds number of mints allowed."); addressToMints[msg.sender]._numberOfMintsByAddress += amount_; for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } if (totalSupply() == MAX_SUPPLY) { phase = SalePhase.Ended; } } // ======== Reveal Metadata ========= function reveal(string memory baseURI_) external onlyEndedPhase onlyZeroIndexShift onlyOwner { baseURI = baseURI_; requestRandomIndexShift(); } // ======== Return Base URI ========= function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // ======== Return Token URI ========= function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { require(_exists(tokenId), "Nonexistent token."); string memory sequenceId; if (indexShift > 0) { sequenceId = Strings.toString((tokenId + indexShift) % MAX_SUPPLY + 1); } else { sequenceId = "0"; } return string(abi.encodePacked(baseURI, sequenceId)); } // ======== Get Total Supply ======== function totalSupply() public view returns (uint256) { return supplyCounter.current(); } // ======== Get Random Number Using Chainlink VRF ========= function requestRandomIndexShift() private returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK."); return requestRandomness(keyHash, fee); } // ======== Set Random Starting Index ========= function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { indexShift = (randomness % MAX_SUPPLY) + 1; } // ======== Verify Coupon ========= function isVerifiedCoupon(bytes32 digest_, Coupon memory coupon_) internal view returns (bool) { address signer = ecrecover(digest_, coupon_.v, coupon_.r, coupon_.s); require(signer != address(0), 'ECDSA: invalid signature'); return signer == ownerSigner; } // ======== Withdraw ========= function withdraw(address payee_, uint256 amount_) external onlyOwner { (bool success, ) = payee_.call{value: amount_}(''); require(success, 'Transfer failed.'); } // ======== Modifiers ======== modifier validateEthPayment(uint256 amount_, uint256 price_) { require(amount_ * price_ <= msg.value, "Ether value sent is not correct."); _; } modifier validateSupply(uint256 amount_) { require(totalSupply() + amount_ <= MAX_SUPPLY, "Max supply exceeded."); _; } modifier validateAmount(uint256 amount_, uint256 max_) { require(amount_ > 0 && amount_ <= max_, "Amount is out of range."); _; } modifier onlyLockedPhase() { require(phase == SalePhase.Locked, "Minting is not locked."); _; } modifier onlyWhitelistPhase() { require(phase == SalePhase.Whitelist, "Whitelist sale is not active."); _; } modifier onlyPrePublicPhase() { require(phase == SalePhase.PrePublic, "PrePublic phase is not active."); _; } modifier onlyPublicPhase() { require(phase == SalePhase.Public, "Public sale is not active."); _; } modifier onlyEndedPhase() { require(phase == SalePhase.Ended, "Sale has not ended."); _; } modifier onlyZeroIndexShift() { require(indexShift == 0, "Already randomized."); _; } } // 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 (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 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/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. 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; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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 // 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 (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/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 (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; 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)); } }
======== Whitelist Mint =========
function whitelistMint(uint256 amount_, Coupon memory coupon_) public payable onlyWhitelistPhase validateAmount(amount_, maxPerAddressWhitelist) validateSupply(amount_) validateEthPayment(amount_, priceWhitelist) nonReentrant { require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressWhitelist, "Exceeds number of whitelist mints allowed."); bytes32 digest = keccak256(abi.encode(CouponType.Whitelist, msg.sender)); require(isVerifiedCoupon(digest, coupon_), "Invalid coupon"); addressToMints[msg.sender]._numberOfMintsByAddress += amount_; for(uint256 ind_ = 0; ind_ < amount_; ind_++) { _safeMint(msg.sender, totalSupply() + 1); supplyCounter.increment(); } if (totalSupply() == MAX_SUPPLY) { phase = SalePhase.Ended; } }
614,599
pragma solidity ^0.5.0; contract Charity { enum CharityStatus {UNVERIFIED, VERIFIED, REJECTED} enum CampaignStatus {ONGOING, ENDED} struct charity { address charityOwner; string charityName; string charityAddress; string contactNumber; string description; string pictureURL; string verificationLink; CharityStatus charityStatus; address[] donors; } struct campaign { uint256 charityId; string campaignName; string description; string pictureURL; uint256 targetDonation; uint256 currentDonation; uint256 noOfDonors; uint256 startDate; uint256 endDate; CampaignStatus campaignStatus; } address contractOwner = msg.sender; mapping(uint256 => bool) isVerifiedCharity; mapping(uint256 => charity) charities; mapping(address => uint256) charityAddressIdMap; mapping(address => charity) charityAddressMap; mapping(address => bool) charityOwnerRegistered; address[] donors; uint256 noOfCharities = 0; uint contractMoney = 0; uint256 charityRegFee = 5 * 10**17; // Reg fee is 0.5 ether, 1 ether is 10**18 wei mapping(uint256 => bool) isOngoingCampaign; mapping(uint256 => campaign) campaigns; uint256 noOfCampaigns = 0; uint256 noOfReturns = 0; modifier onlyOwner(address caller) { require(caller == contractOwner, "Caller is not contract owner"); _; } // This will be the modifier that checks whether the function call is done by the Charity itself. modifier onlyVerifiedCharity(address caller) { require( isVerifiedCharity[charityAddressIdMap[caller]], "Caller is not a valid charity" ); _; } // This will be the modifier that checks whether the function call is done by the Charity or contract owner itself. modifier onlyVerifiedCharityOrOwner(address caller) { require( isVerifiedCharity[charityAddressIdMap[caller]] || caller == contractOwner, "Caller is not a valid charity nor contract owner" ); _; } /* * This will be the function that check the address type * Parameters of this function will include address inputAddress * This function assumes all input address are either contract, charity, or donor */ function checkAddressType( address inputAddress ) public view returns (string memory) { if (inputAddress == contractOwner) { return "CONTRACT"; } else if (charityOwnerRegistered[inputAddress] == true) { return "CHARITYOWNER"; } else { return "DONOR"; } } /* * This will be the function that allows contract owner to withdraw money * There will be no parameters for this function */ function withdrawMoney() public onlyOwner(msg.sender) { require(contractMoney >= 3 * charityRegFee, "Current money is less than 3 * charity register fee"); address payable recipient = address(uint160(address(this))); recipient.transfer(contractMoney); contractMoney = 0; } /* * This fallback function is to make contract address able to receive/make payments */ function() external payable { } /* * This will be the payable function to register the charity * Parameters will be string charityName, string charityAddress, string contactNumber, string description and string pictureURL * Need at least 0.5 ether to register */ function registerCharity( string memory charityName, string memory charityAddress, string memory contactNumber, string memory description, string memory pictureURL ) public payable returns (uint256 charityId) { require( charityOwnerRegistered[msg.sender] == false, "This address has registered another charity already" ); require( msg.value >= charityRegFee, "Need at least 0.5 ether to register a charity" ); contractMoney = contractMoney + msg.value; charityId = noOfCharities++; charity memory newCharity = charity( msg.sender, charityName, charityAddress, contactNumber, description, pictureURL, "", CharityStatus.UNVERIFIED, donors ); charities[charityId] = newCharity; charityAddressIdMap[msg.sender] = charityId; isVerifiedCharity[charityId] = false; charityOwnerRegistered[msg.sender] = true; address payable recipient = address(uint160(contractOwner)); recipient.transfer(msg.value); return charityId; } /* * This will be the function for contract owner to verify the charity * Parameters will be uint charityId, string verification */ function verifyCharity( uint256 charityId, string memory verificationLink ) public onlyOwner(msg.sender) { require(msg.sender == contractOwner, "Caller is not contract owner"); require(charityId < noOfCharities, "Invalid charity id"); require( charities[charityId].charityStatus == CharityStatus.UNVERIFIED, "Charity has been verified or rejected" ); require( isVerifiedCharity[charityId] == false, "Charity has been verified" ); charities[charityId].charityStatus = CharityStatus.VERIFIED; charities[charityId].verificationLink = verificationLink; isVerifiedCharity[charityId] = true; } /* * This will be the function for contract owner to reject the charity * Parameters will be uint charityId, string verification */ function rejectCharity( uint256 charityId ) public onlyOwner(msg.sender) { require(msg.sender == contractOwner, "Caller is not contract owner"); require(charityId < noOfCharities, "Invalid charity id"); require( charities[charityId].charityStatus == CharityStatus.UNVERIFIED, "Charity has been verified or rejected" ); require( isVerifiedCharity[charityId] == false, "Charity has been verified" ); charities[charityId].charityStatus = CharityStatus.REJECTED; } /* * This will be the function for contract owner to revoke the charity * Parameters will be uint charityId, string verification */ function revokeCharity( uint256 charityId ) public onlyOwner(msg.sender) { require(charityId < noOfCharities, "Invalid charity id"); require( charities[charityId].charityStatus == CharityStatus.VERIFIED, "Charity is not a verified charity" ); charities[charityId].charityStatus = CharityStatus.REJECTED; } /* * This will be the function that charities call to create a campaign. * Parameters of this function will include string campaignName, string description, string pictureURL, uint targetDonation (of the campaign), uint startDate (of the campaign), uint endDate (of the campaign) */ function createCampaign( string memory campaignName, string memory description, string memory pictureURL, uint256 targetDonation, uint256 startDate, uint256 endDate ) public onlyVerifiedCharity(msg.sender) returns (uint256 campaignId) { campaignId = noOfCampaigns++; uint256 charityId = charityAddressIdMap[msg.sender]; campaign memory newCampaign = campaign( charityId, campaignName, description, pictureURL, targetDonation, 0, 0, startDate, endDate, CampaignStatus.ONGOING ); campaigns[campaignId] = newCampaign; isOngoingCampaign[campaignId] = true; return campaignId; } /* * This will be the function that charities or contract owner call to end an ongoing campaign. * Parameters of this function will include uint campaignId */ function endCampaign( uint256 campaignId ) public onlyVerifiedCharityOrOwner(msg.sender) { require(campaignId < noOfCampaigns, "Invalid campaign id"); require(isOngoingCampaign[campaignId], "Campaign is not ongoing"); require( msg.sender == charities[campaigns[campaignId].charityId].charityOwner || msg.sender == contractOwner, "Caller is not authorized for this operation" ); campaigns[campaignId].campaignStatus = CampaignStatus.ENDED; isOngoingCampaign[campaignId] = false; } /* * This will be the getter function that everyone can call to check the charity address. * Parameters of this function will include uint charityId */ function getCharityOwner( uint256 charityId ) public view returns (address) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityOwner; } /* * This will be the getter function that everyone can call to check the charity id. * Parameters of this function will include address inputAddress */ function getCharityIdByAddress( address inputAddress ) public view returns (uint256) { require( charityOwnerRegistered[inputAddress] == true, "Address not owner of any charity" ); uint256 charityIdByAddress = charityAddressIdMap[inputAddress]; return charityIdByAddress; } /* * This will be the getter function that everyone can call to check the charity name. * Parameters of this function will include uint charityId */ function getCharityName( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityName; } /* * This will be the getter function that everyone can call to check the charity pictureURL. * Parameters of this function will include uint charityId */ function getCharityPictureURL( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].pictureURL; } /* * This will be the getter function that everyone can call to check the charity pictureURL. * Parameters of this function will include address inputAddress */ function getCharityPictureURLByAddress(address inputAddress) public view returns (string memory) { require( charityOwnerRegistered[inputAddress] == true, "Address not owner of any charity" ); uint256 charityIdByAddress = charityAddressIdMap[inputAddress]; return charities[charityIdByAddress].pictureURL; } /* * This will be the getter function that everyone can call to check the charity description. * Parameters of this function will include uint charityId */ function getCharityDescription( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].description; } /* * This will be the getter function that everyone can call to check the charity status. * Parameters of this function will include uint charityId */ function getCharityStatus( uint256 charityId ) public view returns (CharityStatus) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityStatus; } /* * This will be the getter function that everyone can call to check the charity status. * Parameters of this function will include address inputAddress */ function getCharityStatusByAddress( address inputAddress ) public view returns (CharityStatus) { require( charityOwnerRegistered[inputAddress] == true, "Address not owner of any charity" ); uint256 charityIdByAddress = charityAddressIdMap[inputAddress]; return charities[charityIdByAddress].charityStatus; } /* * This will be the getter function that everyone can call to get the charity contact number. * Parameters of this function will include uint charityId */ function getCharityContactNumber( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].contactNumber; } /* * This will be the getter function that everyone can call to get the charity contact address. * Parameters of this function will include uint charityId */ function getCharityContactAddress( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityAddress; } /* * This will be the getter function that everyone can call to get the charity verification Link. * Parameters of this function will include uint charityId */ function getCharityVerificationLink( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].verificationLink; } /* * This will be the getter function that everyone can call to get the total amounts of the charities. * There will be no parameters for this function */ function getNoOfCharities() public view returns (uint256) { return noOfCharities; } /* * This will be the getter function that everyone can call to check the campaign's charityId. * Parameters of this function will include uint campaignId */ function getCampaignCharity( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].charityId; } /* * This will be the getter function that everyone can call to check the campaign name. * Parameters of this function will include uint campaignId */ function getCampaignName( uint256 campaignId ) public view returns (string memory) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].campaignName; } /* * This will be the getter function that everyone can call to check the campaign description. * Parameters of this function will include uint campaignId */ function getCampaignDescription( uint256 campaignId ) public view returns (string memory) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].description; } /* * This will be the getter function that everyone can call to check the campaign pictureURL. * Parameters of this function will include uint campaignId */ function getCampaignPictureURL( uint256 campaignId ) public view returns (string memory) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].pictureURL; } /* * This will be the getter function that everyone can call to check the campaign targetDonation. * Parameters of this function will include uint campaignId */ function getCampaignTargetDonation( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].targetDonation; } /* * This will be the getter function that everyone can call to check the campaign currentDonation. * Parameters of this function will include uint campaignId */ function getCampaignCurrentDonation( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].currentDonation; } /* * This will be the getter function that everyone can call to check the campaign noOfDonors. * Parameters of this function will include uint campaignId */ function getCampaignNoOfDonors( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].noOfDonors; } /* * This will be the getter function that everyone can call to check the campaign startDate. * Parameters of this function will include uint campaignId */ function getCampaignStartDate( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].startDate; } /* * This will be the getter function that everyone can call to check the campaign endDate. * Parameters of this function will include uint campaignId */ function getCampaignEndDate( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].endDate; } /* * This will be the getter function that everyone can call to check the campaign status. * Parameters of this function will include uint campaignId */ function getCampaignStatus( uint256 campaignId ) public view returns (CampaignStatus) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].campaignStatus; } /* * This will be the getter function that everyone can call to get the total amounts of the campaigns. * There will be no parameters fot this function */ function getNoOfCampaigns() public view returns (uint256) { return noOfCampaigns; } /* *This will be the getter function that everyone can call to check the status of the campaign. * Parameters of this function will include uint campaignId */ function isStatusComplete( uint256 campaignId ) public view returns (bool) { require(campaignId < noOfCampaigns, "Invalid campaign id"); if (campaigns[campaignId].campaignStatus == CampaignStatus.ENDED) { return true; } return false; } /* *This will be the getter function that everyone can call to check if the campagin is valid * Parameters of this function will include uint campaignId */ function checkValidCampaign( uint256 campaignId ) public view returns (bool) { if (campaignId < noOfCampaigns) { return true; } return false; } /* * This will be the function that updates the campaign's currentDonation * Parameters of this function will include uint campaignId and uint newDonation */ function updateCampaignCurrentDonation( uint256 campaignId, uint256 newDonation ) public { require(campaignId < noOfCampaigns, "Invalid campaign id"); uint256 newAmount = campaigns[campaignId].currentDonation + newDonation; campaigns[campaignId].currentDonation = newAmount; } /* * This will be the function that updates the campaign's noOfDonors * Parameters of this function will include uint campaignId */ function addCampaignDonor( uint256 campaignId ) public { require(campaignId < noOfCampaigns, "Invalid campaign id"); uint256 newNumber = campaigns[campaignId].noOfDonors + 1; campaigns[campaignId].noOfDonors = newNumber; } /* * This will be the function that returns the charity's donors * Parameters of this function will include uint campaignId */ function getDonors( uint256 charityId ) public view returns(address[] memory) { address[] memory donorList = charities[charityId].donors; return donorList; } /* * This will be the function that get charity register fee * There will be no parameters for this function */ function getRegFee() public view returns(uint256) { return charityRegFee; } /* * This will be the function to get contract's owner * There will be no parameters for this function */ function getContractOwner() public view returns (address) { return contractOwner; } /* * This will be the function to check if donor has donated to charity before * Parameters of this function will include address donor, uint charityId */ function checkCharityDonor( address donor, uint256 charityId ) public view returns (bool) { uint length = charities[charityId].donors.length; for (uint i = 0; i < length; i++) { if(charities[charityId].donors[i] == donor) { return true; } } return false; } /* * This will be the function to add a new donor to charity * Parameters of this function will include address donor, uint charityId */ function addCharityDonor( address donor, uint256 charityId ) public { charities[charityId].donors.push(donor); } }
This will be the getter function that everyone can call to check the status of the campaign. Parameters of this function will include uint campaignId/
function isStatusComplete( uint256 campaignId ) public view returns (bool) { require(campaignId < noOfCampaigns, "Invalid campaign id"); if (campaigns[campaignId].campaignStatus == CampaignStatus.ENDED) { return true; } return false; }
6,449,594
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./AuthorizationUtilsV0.sol"; import "./TemplateUtilsV0.sol"; import "./WithdrawalUtilsV0.sol"; import "./interfaces/IAirnodeRrpV0.sol"; /// @title Contract that implements the Airnode request–response protocol (RRP) contract AirnodeRrpV0 is AuthorizationUtilsV0, TemplateUtilsV0, WithdrawalUtilsV0, IAirnodeRrpV0 { using ECDSA for bytes32; /// @notice Called to get the sponsorship status for a sponsor–requester /// pair mapping(address => mapping(address => bool)) public override sponsorToRequesterToSponsorshipStatus; /// @notice Called to get the request count of the requester plus one /// @dev Can be used to calculate the ID of the next request the requester /// will make mapping(address => uint256) public override requesterToRequestCountPlusOne; /// @dev Hash of expected fulfillment parameters are kept to verify that /// the fulfillment will be done with the correct parameters. This value is /// also used to check if the fulfillment for the particular request is /// expected, i.e., if there are recorded fulfillment parameters. mapping(bytes32 => bytes32) private requestIdToFulfillmentParameters; /// @notice Called by the sponsor to set the sponsorship status of a /// requester, i.e., allow or disallow a requester to make requests that /// will be fulfilled by the sponsor wallet /// @dev This is not Airnode-specific, i.e., the sponsor allows the /// requester's requests to be fulfilled through its sponsor wallets across /// all Airnodes /// @param requester Requester address /// @param sponsorshipStatus Sponsorship status function setSponsorshipStatus(address requester, bool sponsorshipStatus) external override { // Initialize the requester request count for consistent request gas // cost if (requesterToRequestCountPlusOne[requester] == 0) { requesterToRequestCountPlusOne[requester] = 1; } sponsorToRequesterToSponsorshipStatus[msg.sender][ requester ] = sponsorshipStatus; emit SetSponsorshipStatus(msg.sender, requester, sponsorshipStatus); } /// @notice Called by the requester to make a request that refers to a /// template for the Airnode address, endpoint ID and parameters /// @dev `fulfillAddress` is not allowed to be the address of this /// contract. This is not actually needed to protect users that use the /// protocol as intended, but it is done for good measure. /// @param templateId Template ID /// @param sponsor Sponsor address /// @param sponsorWallet Sponsor wallet that is requested to fulfill the /// request /// @param fulfillAddress Address that will be called to fulfill /// @param fulfillFunctionId Signature of the function that will be called /// to fulfill /// @param parameters Parameters provided by the requester in addition to /// the parameters in the template /// @return requestId Request ID function makeTemplateRequest( bytes32 templateId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata parameters ) external override returns (bytes32 requestId) { address airnode = templates[templateId].airnode; // If the Airnode address of the template is zero the template does not // exist because template creation does not allow zero Airnode address require(airnode != address(0), "Template does not exist"); require(fulfillAddress != address(this), "Fulfill address AirnodeRrp"); require( sponsorToRequesterToSponsorshipStatus[sponsor][msg.sender], "Requester not sponsored" ); uint256 requesterRequestCount = requesterToRequestCountPlusOne[ msg.sender ]; requestId = keccak256( abi.encodePacked( block.chainid, address(this), msg.sender, requesterRequestCount, templateId, sponsor, sponsorWallet, fulfillAddress, fulfillFunctionId, parameters ) ); requestIdToFulfillmentParameters[requestId] = keccak256( abi.encodePacked( airnode, sponsorWallet, fulfillAddress, fulfillFunctionId ) ); requesterToRequestCountPlusOne[msg.sender]++; emit MadeTemplateRequest( airnode, requestId, requesterRequestCount, block.chainid, msg.sender, templateId, sponsor, sponsorWallet, fulfillAddress, fulfillFunctionId, parameters ); } /// @notice Called by the requester to make a full request, which provides /// all of its parameters as arguments and does not refer to a template /// @dev `fulfillAddress` is not allowed to be the address of this /// contract. This is not actually needed to protect users that use the /// protocol as intended, but it is done for good measure. /// @param airnode Airnode address /// @param endpointId Endpoint ID (allowed to be `bytes32(0)`) /// @param sponsor Sponsor address /// @param sponsorWallet Sponsor wallet that is requested to fulfill /// the request /// @param fulfillAddress Address that will be called to fulfill /// @param fulfillFunctionId Signature of the function that will be called /// to fulfill /// @param parameters All request parameters /// @return requestId Request ID function makeFullRequest( address airnode, bytes32 endpointId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata parameters ) external override returns (bytes32 requestId) { require(airnode != address(0), "Airnode address zero"); require(fulfillAddress != address(this), "Fulfill address AirnodeRrp"); require( sponsorToRequesterToSponsorshipStatus[sponsor][msg.sender], "Requester not sponsored" ); uint256 requesterRequestCount = requesterToRequestCountPlusOne[ msg.sender ]; requestId = keccak256( abi.encodePacked( block.chainid, address(this), msg.sender, requesterRequestCount, airnode, endpointId, sponsor, sponsorWallet, fulfillAddress, fulfillFunctionId, parameters ) ); requestIdToFulfillmentParameters[requestId] = keccak256( abi.encodePacked( airnode, sponsorWallet, fulfillAddress, fulfillFunctionId ) ); requesterToRequestCountPlusOne[msg.sender]++; emit MadeFullRequest( airnode, requestId, requesterRequestCount, block.chainid, msg.sender, endpointId, sponsor, sponsorWallet, fulfillAddress, fulfillFunctionId, parameters ); } /// @notice Called by Airnode to fulfill the request (template or full) /// @dev The data is ABI-encoded as a `bytes` type, with its format /// depending on the request specifications. /// This will not revert depending on the external call. However, it will /// return `false` if the external call reverts or if there is no function /// with a matching signature at `fulfillAddress`. On the other hand, it /// will return `true` if the external call returns successfully or if /// there is no contract deployed at `fulfillAddress`. /// If `callSuccess` is `false`, `callData` can be decoded to retrieve the /// revert string. /// This function emits its event after an untrusted low-level call, /// meaning that the order of these events within the transaction should /// not be taken seriously, yet the content will be sound. /// @param requestId Request ID /// @param airnode Airnode address /// @param data Fulfillment data /// @param fulfillAddress Address that will be called to fulfill /// @param fulfillFunctionId Signature of the function that will be called /// to fulfill /// @return callSuccess If the fulfillment call succeeded /// @return callData Data returned by the fulfillment call (if there is /// any) function fulfill( bytes32 requestId, address airnode, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata data, bytes calldata signature ) external override returns (bool callSuccess, bytes memory callData) { require( keccak256( abi.encodePacked( airnode, msg.sender, fulfillAddress, fulfillFunctionId ) ) == requestIdToFulfillmentParameters[requestId], "Invalid request fulfillment" ); require( ( keccak256(abi.encodePacked(requestId, data)) .toEthSignedMessageHash() ).recover(signature) == airnode, "Invalid signature" ); delete requestIdToFulfillmentParameters[requestId]; (callSuccess, callData) = fulfillAddress.call( // solhint-disable-line avoid-low-level-calls abi.encodeWithSelector(fulfillFunctionId, requestId, data) ); if (callSuccess) { emit FulfilledRequest(airnode, requestId, data); } else { // We do not bubble up the revert string from `callData` emit FailedRequest( airnode, requestId, "Fulfillment failed unexpectedly" ); } } /// @notice Called by Airnode if the request cannot be fulfilled /// @dev Airnode should fall back to this if a request cannot be fulfilled /// because static call to `fulfill()` returns `false` for `callSuccess` /// @param requestId Request ID /// @param airnode Airnode address /// @param fulfillAddress Address that will be called to fulfill /// @param fulfillFunctionId Signature of the function that will be called /// to fulfill /// @param errorMessage A message that explains why the request has failed function fail( bytes32 requestId, address airnode, address fulfillAddress, bytes4 fulfillFunctionId, string calldata errorMessage ) external override { require( keccak256( abi.encodePacked( airnode, msg.sender, fulfillAddress, fulfillFunctionId ) ) == requestIdToFulfillmentParameters[requestId], "Invalid request fulfillment" ); delete requestIdToFulfillmentParameters[requestId]; emit FailedRequest(airnode, requestId, errorMessage); } /// @notice Called to check if the request with the ID is made but not /// fulfilled/failed yet /// @dev If a requester has made a request, received a request ID but did /// not hear back, it can call this method to check if the Airnode has /// called back `fail()` instead. /// @param requestId Request ID /// @return isAwaitingFulfillment If the request is awaiting fulfillment /// (i.e., `true` if `fulfill()` or `fail()` is not called back yet, /// `false` otherwise) function requestIsAwaitingFulfillment(bytes32 requestId) external view override returns (bool isAwaitingFulfillment) { isAwaitingFulfillment = requestIdToFulfillmentParameters[requestId] != bytes32(0); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. 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. * * 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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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. * * 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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IAuthorizationUtilsV0.sol"; import "../authorizers/interfaces/IAuthorizerV0.sol"; /// @title Contract that implements authorization checks contract AuthorizationUtilsV0 is IAuthorizationUtilsV0 { /// @notice Uses the authorizer contracts of an Airnode to decide if a /// request is authorized. Once an Airnode receives a request, it calls /// this method to determine if it should respond. Similarly, third parties /// can use this method to determine if a particular request would be /// authorized. /// @dev This method is meant to be called off-chain, statically by the /// Airnode to decide if it should respond to a request. The requester can /// also call it, yet this function returning true should not be taken as a /// guarantee of the subsequent request being fulfilled. /// It is enough for only one of the authorizer contracts to return true /// for the request to be authorized. /// @param authorizers Authorizer contract addresses /// @param airnode Airnode address /// @param requestId Request ID /// @param endpointId Endpoint ID /// @param sponsor Sponsor address /// @param requester Requester address /// @return status Authorization status of the request function checkAuthorizationStatus( address[] calldata authorizers, address airnode, bytes32 requestId, bytes32 endpointId, address sponsor, address requester ) public view override returns (bool status) { for (uint256 ind = 0; ind < authorizers.length; ind++) { IAuthorizerV0 authorizer = IAuthorizerV0(authorizers[ind]); if ( authorizer.isAuthorizedV0( requestId, airnode, endpointId, sponsor, requester ) ) { return true; } } return false; } /// @notice A convenience function to make multiple authorization status /// checks with a single call /// @param authorizers Authorizer contract addresses /// @param airnode Airnode address /// @param requestIds Request IDs /// @param endpointIds Endpoint IDs /// @param sponsors Sponsor addresses /// @param requesters Requester addresses /// @return statuses Authorization statuses of the request function checkAuthorizationStatuses( address[] calldata authorizers, address airnode, bytes32[] calldata requestIds, bytes32[] calldata endpointIds, address[] calldata sponsors, address[] calldata requesters ) external view override returns (bool[] memory statuses) { require( requestIds.length == endpointIds.length && requestIds.length == sponsors.length && requestIds.length == requesters.length, "Unequal parameter lengths" ); statuses = new bool[](requestIds.length); for (uint256 ind = 0; ind < requestIds.length; ind++) { statuses[ind] = checkAuthorizationStatus( authorizers, airnode, requestIds[ind], endpointIds[ind], sponsors[ind], requesters[ind] ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/ITemplateUtilsV0.sol"; /// @title Contract that implements request templates contract TemplateUtilsV0 is ITemplateUtilsV0 { struct Template { address airnode; bytes32 endpointId; bytes parameters; } /// @notice Called to get a template mapping(bytes32 => Template) public override templates; /// @notice Creates a request template with the given parameters, /// addressable by the ID it returns /// @dev A specific set of request parameters will always have the same /// template ID. This means a few things: (1) You can compute the expected /// ID of a template before creating it, (2) Creating a new template with /// the same parameters will overwrite the old one and return the same ID, /// (3) After you query a template with its ID, you can verify its /// integrity by applying the hash and comparing the result with the ID. /// @param airnode Airnode address /// @param endpointId Endpoint ID (allowed to be `bytes32(0)`) /// @param parameters Static request parameters (i.e., parameters that will /// not change between requests, unlike the dynamic parameters determined /// at request-time) /// @return templateId Request template ID function createTemplate( address airnode, bytes32 endpointId, bytes calldata parameters ) external override returns (bytes32 templateId) { require(airnode != address(0), "Airnode address zero"); templateId = keccak256( abi.encodePacked(airnode, endpointId, parameters) ); templates[templateId] = Template({ airnode: airnode, endpointId: endpointId, parameters: parameters }); emit CreatedTemplate(templateId, airnode, endpointId, parameters); } /// @notice A convenience method to retrieve multiple templates with a /// single call /// @dev Does not revert if the templates being indexed do not exist /// @param templateIds Request template IDs /// @return airnodes Array of Airnode addresses /// @return endpointIds Array of endpoint IDs /// @return parameters Array of request parameters function getTemplates(bytes32[] calldata templateIds) external view override returns ( address[] memory airnodes, bytes32[] memory endpointIds, bytes[] memory parameters ) { airnodes = new address[](templateIds.length); endpointIds = new bytes32[](templateIds.length); parameters = new bytes[](templateIds.length); for (uint256 ind = 0; ind < templateIds.length; ind++) { Template storage template = templates[templateIds[ind]]; airnodes[ind] = template.airnode; endpointIds[ind] = template.endpointId; parameters[ind] = template.parameters; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IWithdrawalUtilsV0.sol"; /// @title Contract that implements logic for withdrawals from sponsor wallets contract WithdrawalUtilsV0 is IWithdrawalUtilsV0 { /// @notice Called to get the withdrawal request count of the sponsor /// @dev Can be used to calculate the ID of the next withdrawal request the /// sponsor will make mapping(address => uint256) public override sponsorToWithdrawalRequestCount; /// @dev Hash of expected fulfillment parameters are kept to verify that /// the fulfillment will be done with the correct parameters mapping(bytes32 => bytes32) private withdrawalRequestIdToParameters; /// @notice Called by a sponsor to create a request for the Airnode to send /// the funds kept in the respective sponsor wallet to the sponsor /// @dev We do not need to use the withdrawal request parameters in the /// request ID hash to validate them at the node-side because all of the /// parameters are used during fulfillment and will get validated on-chain. /// The first withdrawal request a sponsor will make will cost slightly /// higher gas than the rest due to how the request counter is implemented. /// @param airnode Airnode address /// @param sponsorWallet Sponsor wallet that the withdrawal is requested /// from function requestWithdrawal(address airnode, address sponsorWallet) external override { bytes32 withdrawalRequestId = keccak256( abi.encodePacked( block.chainid, address(this), msg.sender, ++sponsorToWithdrawalRequestCount[msg.sender] ) ); withdrawalRequestIdToParameters[withdrawalRequestId] = keccak256( abi.encodePacked(airnode, msg.sender, sponsorWallet) ); emit RequestedWithdrawal( airnode, msg.sender, withdrawalRequestId, sponsorWallet ); } /// @notice Called by the Airnode using the sponsor wallet to fulfill the /// withdrawal request made by the sponsor /// @dev The Airnode sends the funds to the sponsor through this method /// to emit an event that indicates that the withdrawal request has been /// fulfilled /// @param withdrawalRequestId Withdrawal request ID /// @param airnode Airnode address /// @param sponsor Sponsor address function fulfillWithdrawal( bytes32 withdrawalRequestId, address airnode, address sponsor ) external payable override { require( withdrawalRequestIdToParameters[withdrawalRequestId] == keccak256(abi.encodePacked(airnode, sponsor, msg.sender)), "Invalid withdrawal fulfillment" ); delete withdrawalRequestIdToParameters[withdrawalRequestId]; emit FulfilledWithdrawal( airnode, sponsor, withdrawalRequestId, msg.sender, msg.value ); (bool success, ) = sponsor.call{value: msg.value}(""); // solhint-disable-line avoid-low-level-calls require(success, "Transfer failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAuthorizationUtilsV0.sol"; import "./ITemplateUtilsV0.sol"; import "./IWithdrawalUtilsV0.sol"; interface IAirnodeRrpV0 is IAuthorizationUtilsV0, ITemplateUtilsV0, IWithdrawalUtilsV0 { event SetSponsorshipStatus( address indexed sponsor, address indexed requester, bool sponsorshipStatus ); event MadeTemplateRequest( address indexed airnode, bytes32 indexed requestId, uint256 requesterRequestCount, uint256 chainId, address requester, bytes32 templateId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes parameters ); event MadeFullRequest( address indexed airnode, bytes32 indexed requestId, uint256 requesterRequestCount, uint256 chainId, address requester, bytes32 endpointId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes parameters ); event FulfilledRequest( address indexed airnode, bytes32 indexed requestId, bytes data ); event FailedRequest( address indexed airnode, bytes32 indexed requestId, string errorMessage ); function setSponsorshipStatus(address requester, bool sponsorshipStatus) external; function makeTemplateRequest( bytes32 templateId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata parameters ) external returns (bytes32 requestId); function makeFullRequest( address airnode, bytes32 endpointId, address sponsor, address sponsorWallet, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata parameters ) external returns (bytes32 requestId); function fulfill( bytes32 requestId, address airnode, address fulfillAddress, bytes4 fulfillFunctionId, bytes calldata data, bytes calldata signature ) external returns (bool callSuccess, bytes memory callData); function fail( bytes32 requestId, address airnode, address fulfillAddress, bytes4 fulfillFunctionId, string calldata errorMessage ) external; function sponsorToRequesterToSponsorshipStatus( address sponsor, address requester ) external view returns (bool sponsorshipStatus); function requesterToRequestCountPlusOne(address requester) external view returns (uint256 requestCountPlusOne); function requestIsAwaitingFulfillment(bytes32 requestId) external view returns (bool isAwaitingFulfillment); } // 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 pragma solidity ^0.8.0; interface IAuthorizationUtilsV0 { function checkAuthorizationStatus( address[] calldata authorizers, address airnode, bytes32 requestId, bytes32 endpointId, address sponsor, address requester ) external view returns (bool status); function checkAuthorizationStatuses( address[] calldata authorizers, address airnode, bytes32[] calldata requestIds, bytes32[] calldata endpointIds, address[] calldata sponsors, address[] calldata requesters ) external view returns (bool[] memory statuses); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IAuthorizerV0 { function isAuthorizedV0( bytes32 requestId, address airnode, bytes32 endpointId, address sponsor, address requester ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ITemplateUtilsV0 { event CreatedTemplate( bytes32 indexed templateId, address airnode, bytes32 endpointId, bytes parameters ); function createTemplate( address airnode, bytes32 endpointId, bytes calldata parameters ) external returns (bytes32 templateId); function getTemplates(bytes32[] calldata templateIds) external view returns ( address[] memory airnodes, bytes32[] memory endpointIds, bytes[] memory parameters ); function templates(bytes32 templateId) external view returns ( address airnode, bytes32 endpointId, bytes memory parameters ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWithdrawalUtilsV0 { event RequestedWithdrawal( address indexed airnode, address indexed sponsor, bytes32 indexed withdrawalRequestId, address sponsorWallet ); event FulfilledWithdrawal( address indexed airnode, address indexed sponsor, bytes32 indexed withdrawalRequestId, address sponsorWallet, uint256 amount ); function requestWithdrawal(address airnode, address sponsorWallet) external; function fulfillWithdrawal( bytes32 withdrawalRequestId, address airnode, address sponsor ) external payable; function sponsorToWithdrawalRequestCount(address sponsor) external view returns (uint256 withdrawalRequestCount); }
Called by Airnode if the request cannot be fulfilled Airnode should fall back to this if a request cannot be fulfilled because static call to `fulfill()` returns `false` for `callSuccess` requestId Request ID airnode Airnode address fulfillAddress Address that will be called to fulfill fulfillFunctionId Signature of the function that will be called to fulfill errorMessage A message that explains why the request has failed
function fail( bytes32 requestId, address airnode, address fulfillAddress, bytes4 fulfillFunctionId, string calldata errorMessage ) external override { require( keccak256( abi.encodePacked( airnode, msg.sender, fulfillAddress, fulfillFunctionId ) ) == requestIdToFulfillmentParameters[requestId], "Invalid request fulfillment" ); delete requestIdToFulfillmentParameters[requestId]; emit FailedRequest(airnode, requestId, errorMessage); }
11,959,939
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @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() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract MintableToken is StandardToken, Ownable, Pausable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; uint256 public constant maxTokensToMint = 1000000000 ether; uint256 public constant maxTokensToBuy = 600000000 ether; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyOwner returns (bool) { return mintInternal(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() whenNotPaused onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } function mintInternal(address _to, uint256 _amount) internal canMint returns (bool) { require(totalSupply.add(_amount) <= maxTokensToMint); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(this, _to, _amount); return true; } } contract Test is MintableToken { string public constant name = "HIH"; string public constant symbol = "HIH"; bool public preIcoActive = false; bool public preIcoFinished = false; bool public icoActive = false; bool public icoFinished = false; bool public transferEnabled = false; uint8 public constant decimals = 18; uint256 public constant maxPreIcoTokens = 100000000 ether; uint256 public preIcoTokensCount = 0; uint256 public tokensForIco = 600000000 ether; address public wallet = 0xa74fF9130dBfb9E326Ad7FaE2CAFd60e52129CF0; uint256 public dateStart = 1511987870; uint256 public rateBase = 35000; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); /** * @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, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this) && _to != address(0)); return super.transfer(_to, _value); } /** * @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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this) && _to != address(0)); return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev Modifier to make a function callable only when the transfer is enabled. */ modifier canTransfer() { require(transferEnabled); _; } /** * @dev Function to stop transfering tokens. * @return True if the operation was successful. */ function enableTransfer() onlyOwner returns (bool) { transferEnabled = true; return true; } function startPre() onlyOwner returns (bool) { require(!preIcoActive && !preIcoFinished && !icoActive && !icoFinished); preIcoActive = true; dateStart = block.timestamp; return true; } function finishPre() onlyOwner returns (bool) { require(preIcoActive && !preIcoFinished && !icoActive && !icoFinished); preIcoActive = false; tokensForIco = maxTokensToBuy.sub(totalSupply); preIcoTokensCount = totalSupply; preIcoFinished = true; return true; } function startIco() onlyOwner returns (bool) { require(!preIcoActive && preIcoFinished && !icoActive && !icoFinished); icoActive = true; return true; } function finishIco() onlyOwner returns (bool) { require(!preIcoActive && preIcoFinished && icoActive && !icoFinished); icoActive = false; icoFinished = true; return true; } modifier canBuyTokens() { require(preIcoActive || icoActive); require(block.timestamp >= dateStart); _; } function () payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) whenNotPaused canBuyTokens payable { require(beneficiary != 0x0); require(msg.value > 0); require(msg.value >= 10 finney); uint256 weiAmount = msg.value; uint256 tokens = 0; if(preIcoActive){ tokens = buyPreIcoTokens(weiAmount); }else if(icoActive){ tokens = buyIcoTokens(weiAmount); } mintInternal(beneficiary, tokens); forwardFunds(); } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } function changeWallet(address _newWallet) onlyOwner returns (bool) { require(_newWallet != 0x0); wallet = _newWallet; return true; } function buyPreIcoTokens(uint256 _weiAmount) internal returns(uint256){ uint8 percents = 0; if(block.timestamp - dateStart <= 10 days){ percents = 20; } if(block.timestamp - dateStart <= 8 days){ percents = 40; } if(block.timestamp - dateStart <= 6 days){ percents = 60; } if(block.timestamp - dateStart <= 4 days){ percents = 80; } if(block.timestamp - dateStart <= 2 days){ // first week percents = 100; } uint256 tokens = _weiAmount.mul(rateBase).mul(2); if(percents > 0){ tokens = tokens.add(tokens.mul(percents).div(100)); // add bonus } require(totalSupply.add(tokens) <= maxPreIcoTokens); return tokens; } function buyIcoTokens(uint256 _weiAmount) internal returns(uint256){ uint256 rate = getRate(); uint256 tokens = _weiAmount.mul(rate); tokens = tokens.add(tokens.mul(30).div(100)); // add bonus require(totalSupply.add(tokens) <= maxTokensToBuy); return tokens; } function getRate() internal returns(uint256){ uint256 rate = rateBase; uint256 step = tokensForIco.div(5); uint8 additionalPercents = 0; if(totalSupply < step){ additionalPercents = 0; }else{ uint256 currentRound = totalSupply.sub(preIcoTokensCount).div(step); if(currentRound >= 4){ additionalPercents = 30; } if(currentRound >= 3 && currentRound < 4){ additionalPercents = 30; } if(currentRound >= 2&& currentRound < 3){ additionalPercents = 20; } if(currentRound >= 1 && currentRound < 2){ additionalPercents = 10; } } if(additionalPercents > 0){ rate -= rateBase.mul(additionalPercents).div(100); // add bonus } return rate; } function setDateStart(uint256 _dateStart) onlyOwner returns (bool) { require(_dateStart > block.timestamp); dateStart = _dateStart; return true; } function setRate(uint256 _rate) onlyOwner returns (bool) { require(_rate > 0); rateBase = _rate; return true; } }
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; }
543,568
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // 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; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() 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; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(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 MUL16(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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(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 MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(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 TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(address p0, bool p1, string memory p2, address p3) internal view {
1,019,191
pragma solidity 0.5.0; import "./SafeMath.sol"; import "./RewardContract.sol"; import "./Adbank.sol"; contract AdbankRewardClaimContract is RewardContract { using SafeMath for uint256; // Stop contract from executing it's main logic bool public suspended; // Limit the size of incoming requests (assignRewards and claimRewards functions) uint8 public batchLimit; address public owner; mapping(bytes32 => uint256) public balances; uint256 public totalReward; // AdBank contract that is used for the actual transfers Adbank public adbankContract; // Functions with this modifier can only be executed by the owner modifier onlyOwner() { require (msg.sender == owner); _; } // Functions with this modifier can only be executed if execution is not suspended modifier notSuspended() { require (suspended == false); _; } constructor(address _adbankContract, uint8 _batchLimit) public { owner = msg.sender; suspended = false; totalReward = 0; adbankContract = Adbank(_adbankContract); batchLimit = _batchLimit; } // Suspend / resume the execution of contract methods function suspend(bool _suspended) external onlyOwner { suspended = _suspended; } // Change owner function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0x0)); owner = _newOwner; } // Drain all funds. Returns tokens to the contract owner function drain() external onlyOwner { uint256 contractBalance = adbankContract.balanceOf(address(this)); require(contractBalance > 0); require(transferReward(owner, contractBalance)); suspended = true; } // Change the requests limit function setBatchLimit(uint8 newLimit) onlyOwner external { require(newLimit > 0); batchLimit = newLimit; } // Change the Adbank contract function setAdbankContract(address _adbankContract) onlyOwner external { require(_adbankContract != address(0x0)); adbankContract = Adbank(_adbankContract); } // Get user balance according to user's blade id function balanceOf(bytes32 _bladeId) public view returns (uint256 balance) { return balances[_bladeId]; } // Assign rewards according to user's blade ids. // The size of incoming data is limited to be in (0;batchLimit] range // Requires this contract to have token balance to cover the incoming rewards function assignRewards(bytes32[] calldata _bladeIds, uint256[] calldata _rewards) notSuspended onlyOwner external { require(_bladeIds.length > 0 && _bladeIds.length <= batchLimit); require(_bladeIds.length == _rewards.length); for (uint8 i = 0; i < _bladeIds.length; i++) { balances[_bladeIds[i]] = (balances[_bladeIds[i]]).add(_rewards[i]); totalReward = (totalReward).add(_rewards[i]); emit RewardAssigned(_bladeIds[i], _rewards[i]); } require(hasEnoughBalance()); } // Claim rewards according to user's blade ids. // The size of incoming data is limited to be in (0;batchLimit] range // Requires this contract to have token balance to cover the rewards function claimRewards(bytes32[] calldata _bladeIds, address[] calldata _wallets) notSuspended onlyOwner external { require(_bladeIds.length > 0 && _bladeIds.length <= batchLimit); require(_bladeIds.length == _wallets.length); require(hasEnoughBalance()); for (uint8 i = 0; i < _bladeIds.length; i++) { processReward(_bladeIds[i], _wallets[i], false); } } // Claim reward for the specified user function claimReward(bytes32 _bladeId, address _to) notSuspended onlyOwner external returns (bool ok) { return processReward(_bladeId, _to, true); } // Send the reward and return result. // Will throw exception or skip the execution depending on the _requireValid param function processReward(bytes32 _bladeId, address _to, bool _requireValid) notSuspended onlyOwner internal returns (bool ok) { bool valid = validAddressAndBalance(_to, _bladeId); if (_requireValid) { require(valid); } else if (!valid) { return false; } uint256 rewardToSend = balances[_bladeId]; balances[_bladeId] = 0; totalReward = (totalReward).sub(rewardToSend); bool transferStatus = transferReward(_to, rewardToSend); emit RewardClaimed(_bladeId, _to, rewardToSend); return transferStatus; } // Do the actual transfer of the reward to the specified address function transferReward(address _to, uint256 _amount) onlyOwner internal returns (bool ok) { bool result = adbankContract.transfer(_to, _amount); require(result); return result; } // Check that address is valid, user has balance and contract has enough balance function validAddressAndBalance(address _address, bytes32 _bladeId) internal view returns (bool valid) { if (_address != address(0x0) && balances[_bladeId] > 0) { return true; } return false; } // Check that contract has enough tokens to cover transactions with rewards function hasEnoughBalance() public view returns (bool enoughBalance) { return adbankContract.balanceOf(address(this)) >= totalReward; } }
Suspend / resume the execution of contract methods
function suspend(bool _suspended) external onlyOwner { suspended = _suspended; }
534,307
// SPDX-License-Identifier: GPLv2 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../DigitalaxAccessControls.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IDigitalaxRewards.sol"; import "../EIP2771/BaseRelayRecipient.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title Digitalax Staking * @dev Stake MONA tokens, earn MONA on the Digitalax platform * @author DIGITALAX CORE TEAM * @author Based on original staking contract by Adrian Guerrera (deepyr) */ contract DigitalaxMonaStaking is BaseRelayRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public monaToken; // MONA ERC20s uint256 public MAX_NUMBER_OF_POOLS = 20; uint256 constant SECONDS_IN_A_DAY = 86400; DigitalaxAccessControls public accessControls; IDigitalaxRewards public rewardsContract; /** @notice Struct to track what user is staking which tokens @dev balance is the current ether balance of the staker @dev lastRewardPoints is the amount of rewards (revenue) that were accumulated at the last checkpoint @dev cycleStartTimestamp is the timestamp their cycle starts. This is only reset if someone unstakes 100% and resets. Any earnings are pro-rata if stake is increased @dev monaRevenueRewardsEarned is the total reward for the staker till now - revenue sharing @dev rewardsReleased is how much reward has been paid to the staker - revenue sharing @dev isEarlyRewardsStaker is whether this staker qualifies as an early bird for extra bonus @dev earlyRewardsEarned the amount of early rewards earned so far by staker @dev earlyRewardsReleased is the amount of early rewards that have been released to the staker @dev monaMintingRewardsEarned the amount of mona minted rewards earned so far by staker @dev earlyRewardsReleased is the amount of mona minted rewardsthat have been released to the staker @dev ethDepositRewardsEarned the amount of ETH rewards earned so far by staker @dev ethDepositRewardsReleased is the amount of ETH rewards that have been released to the staker */ struct Staker { uint256 balance; uint256 lastRewardPoints; uint256 lastBonusRewardPoints; uint256 lastRewardUpdateTime; uint256 cycleStartTimestamp; uint256 monaRevenueRewardsPending; uint256 bonusMonaRevenueRewardsPending; uint256 monaRevenueRewardsEarned; uint256 monaRevenueRewardsReleased; bool isEarlyRewardsStaker; } /** @notice Struct to track the active pools @dev stakers is a mapping of existing stakers in the pool @dev lastUpdateTime last time the pool was updated with rewards per token points @dev rewardsPerTokenPoints amount of rewards overall for that pool (revenue sharing) @dev daysInCycle the number of minimum days to stake, the length of a cycle (e.g. 30, 90, 180 days) @dev minimumStakeInMona the minimum stake to be in the pool @dev maximumStakeInMona the maximum stake to be in the pool @dev maximumNumberOfStakersInPool maximum total number of stakers that can get into this pool @dev maximumNumberOfEarlyRewardsUsers number of people that receive early rewards for staking early @dev currentNumberOfEarlyRewardsUsers number of people that have staked early */ struct StakingPool { mapping (address => Staker) stakers; uint256 stakedMonaTotalForPool; uint256 earlyStakedMonaTotalForPool; uint256 lastUpdateTime; uint256 rewardsPerTokenPoints; uint256 bonusRewardsPerTokenPoints; uint256 daysInCycle; uint256 minimumStakeInMona; uint256 maximumStakeInMona; uint256 currentNumberOfStakersInPool; uint256 maximumNumberOfStakersInPool; uint256 maximumNumberOfEarlyRewardsUsers; uint256 currentNumberOfEarlyRewardsUsers; } /* * @notice mapping of Pool Id's to pools */ mapping (uint256 => StakingPool) pools; uint256 public numberOfStakingPools = 0; /* * @notice the total mona staked over all pools */ uint256 public stakedMonaTotal; uint256 public earlyStakedMonaTotal; uint256 constant pointMultiplier = 10e32; /* * @notice sets the token to be claimable or not, cannot claim if it set to false */ bool public tokensClaimable = true; /* ========== Events ========== */ event UpdateAccessControls( address indexed accessControls ); /* * @notice event emitted when a pool is initialized */ event PoolInitialized( uint256 poolId, uint256 _daysInCycle, uint256 _minimumStakeInMona, uint256 _maximumStakeInMona, uint256 _maximumNumberOfStakersInPool, uint256 _maximumNumberOfEarlyRewardsUsers); /* * @notice event emitted when a user has staked a token */ event Staked(address indexed owner, uint256 amount); /* * @notice event emitted when a user has unstaked a token */ event Unstaked(address indexed owner, uint256 amount); /* * @notice event emitted when a user claims reward */ event MonaRevenueRewardPaid(address indexed user, uint256 reward); event ClaimableStatusUpdated(bool status); event EmergencyUnstake(address indexed user, uint256 amount); event MonaTokenUpdated(address indexed oldMonaToken, address newMonaToken ); event RewardsTokenUpdated(address indexed oldRewardsToken, address newRewardsToken ); event ReclaimedERC20(address indexed token, uint256 amount); constructor(address _monaToken, DigitalaxAccessControls _accessControls, address _trustedForwarder) public { require(_monaToken != address(0), "DigitalaxMonaStaking: Invalid Mona Token"); require(address(_accessControls) != address(0), "DigitalaxMonaStaking: Invalid Access Controls"); monaToken = _monaToken; accessControls = _accessControls; trustedForwarder = _trustedForwarder; } receive() external payable { require( _msgSender() == address(rewardsContract), "DigitalaxMonaStaking.receive: Sender must be rewards contract" ); } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } /* * @notice Lets admin set the Rewards Token */ function setRewardsContract( address _addr ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.setRewardsContract: Sender must be admin" ); require(_addr != address(0)); address oldAddr = address(rewardsContract); rewardsContract = IDigitalaxRewards(_addr); emit RewardsTokenUpdated(oldAddr, _addr); } /* * @notice Lets admin set the max number of staking pools */ function setMaxNumberOfPools( uint256 _max ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.setMaxNumberOfPools: Sender must be admin" ); require(_max >= numberOfStakingPools); MAX_NUMBER_OF_POOLS = _max; } /** * @dev Single gateway to intialize the staking contract pools after deploying * @dev Sets the contract with the MONA token */ function initMonaStakingPool( uint256 _daysInCycle, uint256 _minimumStakeInMona, uint256 _maximumStakeInMona, uint256 _maximumNumberOfStakersInPool, uint256 _maximumNumberOfEarlyRewardsUsers) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.initMonaStakingPool: Sender must be admin" ); require( numberOfStakingPools < MAX_NUMBER_OF_POOLS, "DigitalaxMonaStaking.initMonaStakingPool: Contract already reached max number of supported pools" ); require( _daysInCycle > 0, "DigitalaxMonaStaking.initMonaStakingPool: Must be more then one day in the cycle" ); require( _minimumStakeInMona > 0, "DigitalaxMonaStaking.initMonaStakingPool: The minimum stake in Mona must be greater than zero" ); require( _maximumStakeInMona >= _minimumStakeInMona, "DigitalaxMonaStaking.initMonaStakingPool: The maximum stake in Mona must be greater than or equal to the minimum stake" ); StakingPool storage stakingPool = pools[numberOfStakingPools]; stakingPool.daysInCycle = _daysInCycle; stakingPool.minimumStakeInMona = _minimumStakeInMona; stakingPool.maximumStakeInMona = _maximumStakeInMona; stakingPool.currentNumberOfStakersInPool = 0; stakingPool.maximumNumberOfStakersInPool = _maximumNumberOfStakersInPool; stakingPool.currentNumberOfEarlyRewardsUsers = 0; stakingPool.maximumNumberOfStakersInPool = _maximumNumberOfStakersInPool; stakingPool.maximumNumberOfEarlyRewardsUsers = _maximumNumberOfEarlyRewardsUsers; stakingPool.lastUpdateTime = _getNow(); // Emit event with this pools id index, and increment the number of staking pools that exist emit PoolInitialized(numberOfStakingPools, _daysInCycle, _minimumStakeInMona, _maximumStakeInMona, _maximumNumberOfStakersInPool, _maximumNumberOfEarlyRewardsUsers); numberOfStakingPools = numberOfStakingPools.add(1); } /* * @notice Lets admin set the Mona Token */ function setMonaToken( address _addr ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.setMonaToken: Sender must be admin" ); require(_addr != address(0), "DigitalaxMonaStaking.setMonaToken: Invalid Mona Token"); address oldAddr = monaToken; monaToken = _addr; emit MonaTokenUpdated(oldAddr, _addr); } /* * @notice Lets admin set when tokens are claimable */ function setTokensClaimable( bool _enabled ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.setTokensClaimable: Sender must be admin" ); tokensClaimable = _enabled; emit ClaimableStatusUpdated(_enabled); } /** @notice Method for updating the access controls contract used by the NFT @dev Only admin @param _accessControls Address of the new access controls contract (Cannot be zero address) */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.updateAccessControls: Sender must be admin" ); require(address(_accessControls) != address(0), "DigitalaxMonaStaking.updateAccessControls: Zero Address"); accessControls = _accessControls; emit UpdateAccessControls(address(_accessControls)); } /* @notice Getter functions for Staking contract * @dev Get the tokens staked by a user */ function getStakedBalance( uint256 _poolId, address _user ) external view returns (uint256 balance) { return pools[_poolId].stakers[_user].balance; } /* * @dev Get the total ETH staked (all pools) */ function stakedMonaInPool(uint256 _poolId) external view returns (uint256) { return pools[_poolId].stakedMonaTotalForPool; } /* * @dev Get the total ETH staked (all pools early stakers) */ function earlyStakedMonaInPool(uint256 _poolId) external view returns (uint256) { return pools[_poolId].earlyStakedMonaTotalForPool; } /* * @dev Get the total ETH staked (all pools) */ function stakedEthTotal() external view returns (uint256) { uint256 monaPerEth = getMonaTokenPerEthUnit(1e18); return stakedMonaTotal.mul(1e18).div(monaPerEth); } /* * @dev Get the total early ETH staked (all pools) */ function earlyStakedEthTotal() external view returns (uint256) { uint256 monaPerEth = getMonaTokenPerEthUnit(1e18); return earlyStakedMonaTotal.mul(1e18).div(monaPerEth); } /* * @dev Get the total ETH staked (all pools) */ function stakedEthTotalByPool(uint256 _poolId) external view returns (uint256) { uint256 monaPerEth = getMonaTokenPerEthUnit(1e18); return pools[_poolId].stakedMonaTotalForPool.mul(1e18).div(monaPerEth); } /* * @dev Get the total ETH staked (all pools) */ function earlyStakedEthTotalByPool(uint256 _poolId) external view returns (uint256) { uint256 monaPerEth = getMonaTokenPerEthUnit(1e18); return pools[_poolId].earlyStakedMonaTotalForPool.mul(1e18).div(monaPerEth); } /* * @notice Stake MONA Tokens and earn rewards. */ function stake( uint256 _poolId, uint256 _amount ) external { _stake(_poolId, _msgSender(), _amount); } /* * @notice Stake All MONA Tokens in your wallet and earn rewards. */ function stakeAll(uint256 _poolId) external { uint256 balance = IERC20(monaToken).balanceOf(_msgSender()); _stake(_poolId, _msgSender(), balance); } /** * @dev All the staking goes through this function * @dev Rewards to be given out is calculated * @dev Balance of stakers are updated as they stake the nfts based on ether price */ function _stake( uint256 _poolId, address _user, uint256 _amount ) internal { require( _amount > 0 , "DigitalaxMonaStaking._stake: Staked amount must be greater than 0" ); StakingPool storage stakingPool = pools[_poolId]; Staker storage staker = stakingPool.stakers[_user]; require( staker.balance.add(_amount) >= stakingPool.minimumStakeInMona, "DigitalaxMonaStaking._stake: Staked amount must be greater than or equal to minimum stake" ); require( staker.balance.add(_amount) <= stakingPool.maximumStakeInMona, "DigitalaxMonaStaking._stake: Staked amount must be less than or equal to maximum stake" ); // Check if a new user if(staker.lastRewardUpdateTime == 0 && staker.balance == 0) { require( stakingPool.currentNumberOfStakersInPool < stakingPool.maximumNumberOfStakersInPool, "DigitalaxMonaStaking._stake: This pool is already full" ); stakingPool.currentNumberOfStakersInPool = stakingPool.currentNumberOfStakersInPool.add(1); // Check if an early staker if(stakingPool.currentNumberOfEarlyRewardsUsers < stakingPool.maximumNumberOfEarlyRewardsUsers){ stakingPool.currentNumberOfEarlyRewardsUsers = stakingPool.currentNumberOfEarlyRewardsUsers.add(1); staker.isEarlyRewardsStaker = true; } else { staker.isEarlyRewardsStaker = false; } } if(staker.balance == 0) { staker.cycleStartTimestamp = _getNow(); if (staker.lastRewardPoints == 0 ) { staker.lastRewardPoints = stakingPool.rewardsPerTokenPoints; } if(staker.isEarlyRewardsStaker && (staker.lastBonusRewardPoints == 0)){ staker.lastBonusRewardPoints = stakingPool.bonusRewardsPerTokenPoints; } } updateReward(_poolId, _user); staker.balance = staker.balance.add(_amount); stakedMonaTotal = stakedMonaTotal.add(_amount); stakingPool.stakedMonaTotalForPool = stakingPool.stakedMonaTotalForPool.add(_amount); if(staker.isEarlyRewardsStaker){ earlyStakedMonaTotal = earlyStakedMonaTotal.add(_amount); stakingPool.earlyStakedMonaTotalForPool = stakingPool.earlyStakedMonaTotalForPool.add(_amount); } IERC20(monaToken).safeTransferFrom( address(_user), address(this), _amount ); emit Staked(_user, _amount); } /* * @notice Unstake MONA Tokens. */ function unstake( uint256 _poolId, uint256 _amount ) external { _unstake(_poolId, _msgSender(), _amount); } /** * @dev All the unstaking goes through this function * @dev Rewards to be given out is calculated * @dev Balance of stakers are updated as they unstake the nfts based on ether price */ function _unstake( uint256 _poolId, address _user, uint256 _amount ) internal { require( pools[_poolId].stakers[_user].balance >= _amount, "DigitalaxMonaStaking._unstake: Sender must have staked tokens" ); _claimReward(_poolId, _user); Staker storage staker = pools[_poolId].stakers[_user]; staker.balance = staker.balance.sub(_amount); stakedMonaTotal = stakedMonaTotal.sub(_amount); pools[_poolId].stakedMonaTotalForPool = pools[_poolId].stakedMonaTotalForPool.sub(_amount); if(staker.isEarlyRewardsStaker){ earlyStakedMonaTotal = earlyStakedMonaTotal.sub(_amount); pools[_poolId].earlyStakedMonaTotalForPool = pools[_poolId].earlyStakedMonaTotalForPool.sub(_amount); } if (staker.balance == 0) { delete pools[_poolId].stakers[_user]; // TODO figure out if this is still valid } uint256 tokenBal = IERC20(monaToken).balanceOf(address(this)); if (_amount > tokenBal) { IERC20(monaToken).safeTransfer(address(_user), tokenBal); } else { IERC20(monaToken).safeTransfer(address(_user), _amount); } emit Unstaked(_user, _amount); } /* * @notice Unstake without caring about rewards. EMERGENCY ONLY. */ function emergencyUnstake(uint256 _poolId) external { uint256 amount = pools[_poolId].stakers[_msgSender()].balance; pools[_poolId].stakers[_msgSender()].balance = 0; pools[_poolId].stakers[_msgSender()].monaRevenueRewardsEarned = 0; IERC20(monaToken).safeTransfer(address(_msgSender()), amount); emit EmergencyUnstake(_msgSender(), amount); } /* * @dev Updates the amount of rewards owed for each user before any tokens are moved */ function updateReward( uint256 _poolId, address _user ) public { StakingPool storage stakingPool = pools[_poolId]; require(stakingPool.daysInCycle > 0, "DigitalaxMonaStaking.updateRewards: This pool has not been instantiated"); // 1 Updates the amount of rewards, transfer MONA to this contract so there is some balance rewardsContract.updateRewards(_poolId); // 2 Calculates the overall amount of mona revenue that has increased since the last time someone called this method uint256 monaRewards = rewardsContract.MonaRevenueRewards(_poolId, stakingPool.lastUpdateTime, _getNow()); // Continue if there is mona in this pool if (stakingPool.stakedMonaTotalForPool > 0) { // 3 Update the overall rewards per token points with the new mona rewards stakingPool.rewardsPerTokenPoints = stakingPool.rewardsPerTokenPoints.add(monaRewards .mul(1e18) .mul(pointMultiplier) .div(stakingPool.stakedMonaTotalForPool)); } // 2 Calculates the bonus overall amount of mona revenue that has increased since the last time someone called this method uint256 bonusMonaRewards = rewardsContract.BonusMonaRevenueRewards(_poolId, stakingPool.lastUpdateTime, _getNow()); // Continue if there is mona in this pool if (stakingPool.earlyStakedMonaTotalForPool > 0) { // 3 Update the overall rewards per token points with the new mona rewards stakingPool.bonusRewardsPerTokenPoints = stakingPool.bonusRewardsPerTokenPoints.add(bonusMonaRewards .mul(1e18) .mul(pointMultiplier) .div(stakingPool.earlyStakedMonaTotalForPool)); } // 4 Update the last update time for this pool, calculating overall rewards stakingPool.lastUpdateTime = _getNow(); // 5 Calculate the rewards owing overall for this user uint256 rewards = rewardsOwing(_poolId, _user); // There are 2 states. // 1. We are in the same cycle and need to add pending rewards, // 2. If we are in a new cycle, all pending rewards get added to monaRevenueRewardsEarned // If we are in a new cycle, we will add subtract from the last cycle start until now // to see what is new pending rewards and what is monaRevenueRewardsEarned Staker storage staker = stakingPool.stakers[_user]; uint256 bonusRewards = 0; if(staker.isEarlyRewardsStaker){ bonusRewards = bonusRewardsOwing(_poolId, _user); } uint256 secondsInCycle = stakingPool.daysInCycle.mul(SECONDS_IN_A_DAY); uint256 timeElapsedSinceStakingFromZero = _getNow().sub(staker.cycleStartTimestamp); uint256 startOfCurrentCycle = _getNow().sub(timeElapsedSinceStakingFromZero.mod(secondsInCycle)); if (_user != address(0)) { // Check what state we are in TODO check this next line closely for accuracy of when cycle starts if(startOfCurrentCycle > staker.lastRewardUpdateTime) { // We are in a new cycle // Bring over the pending rewards, they have been earned rewards = rewards.add(staker.monaRevenueRewardsPending); bonusRewards = bonusRewards.add(staker.bonusMonaRevenueRewardsPending); uint256 monaPendingRewardsTotal = rewardsContract.MonaRevenueRewards(_poolId, startOfCurrentCycle, _getNow()).mul(1e18); uint256 pendingRewardsThisCycle = staker.balance.mul(monaPendingRewardsTotal); pendingRewardsThisCycle = pendingRewardsThisCycle.div(stakingPool.stakedMonaTotalForPool); // In case it overflows pendingRewardsThisCycle = pendingRewardsThisCycle.div(1e18); staker.monaRevenueRewardsPending = pendingRewardsThisCycle; rewards = rewards.sub(pendingRewardsThisCycle); // Set rewards (This includes old pending rewards and does not include new pending rewards) staker.monaRevenueRewardsEarned = staker.monaRevenueRewardsEarned.add(rewards); // Early staker if(staker.isEarlyRewardsStaker){ uint256 bonusMonaPendingRewardsTotal = rewardsContract.BonusMonaRevenueRewards(_poolId, startOfCurrentCycle, _getNow()); bonusMonaPendingRewardsTotal = bonusMonaPendingRewardsTotal.mul(1e18); uint256 bonusPendingRewardsThisCycle = staker.balance.mul(bonusMonaPendingRewardsTotal); bonusPendingRewardsThisCycle = bonusPendingRewardsThisCycle.div(stakingPool.earlyStakedMonaTotalForPool); bonusPendingRewardsThisCycle = bonusPendingRewardsThisCycle.div(1e18); staker.bonusMonaRevenueRewardsPending = bonusPendingRewardsThisCycle; bonusRewards = bonusRewards.sub(bonusPendingRewardsThisCycle); staker.monaRevenueRewardsEarned = staker.monaRevenueRewardsEarned.add(bonusRewards); } staker.lastRewardPoints = stakingPool.rewardsPerTokenPoints; staker.lastRewardUpdateTime = _getNow(); } else { // We are still in the same cycle as the last reward update, add rewards then bonus rewards staker.monaRevenueRewardsPending = staker.monaRevenueRewardsPending.add(rewards); if(staker.isEarlyRewardsStaker){ staker.bonusMonaRevenueRewardsPending = staker.monaRevenueRewardsPending.add(bonusRewards); staker.lastBonusRewardPoints = stakingPool.bonusRewardsPerTokenPoints; } staker.lastRewardPoints = stakingPool.rewardsPerTokenPoints; staker.lastRewardUpdateTime = _getNow(); } } } /* * @dev The rewards are dynamic and normalised from the other pools * @dev This gets the rewards from each of the periods as one multiplier */ function rewardsOwing( uint256 _poolId, address _user ) public view returns(uint256) { uint256 newRewardPerToken = pools[_poolId].rewardsPerTokenPoints.sub(pools[_poolId].stakers[_user].lastRewardPoints); uint256 rewards = pools[_poolId].stakers[_user].balance.mul(newRewardPerToken) .div(1e18) .div(pointMultiplier); return rewards; } /* * @dev The bonus rewards are dynamic and normalised from the other pools * @dev This gets the rewards from each of the periods as one multiplier */ function bonusRewardsOwing( uint256 _poolId, address _user ) public view returns(uint256) { uint256 newRewardPerToken = pools[_poolId].bonusRewardsPerTokenPoints.sub(pools[_poolId].stakers[_user].lastBonusRewardPoints); uint256 bonusRewards = pools[_poolId].stakers[_user].balance.mul(newRewardPerToken) .div(1e18) .div(pointMultiplier); return bonusRewards; } /* * @notice Returns the about of rewards yet to be claimed (this currently includes pending and awarded together * @param _poolId the id of the pool we are interested in * @param _user the user we are interested in * @dev returns the claimable rewards and pending rewards */ // TODO stack too deep function unclaimedRewards( uint256 _poolId, address _user ) public view returns(uint256 claimableRewards, uint256 pendingRewards) { StakingPool storage stakingPool = pools[_poolId]; if (stakingPool.stakedMonaTotalForPool == 0) { return (0,0); } Staker storage staker = stakingPool.stakers[_user]; uint256 monaRewards = rewardsContract.MonaRevenueRewards(_poolId, stakingPool.lastUpdateTime, _getNow()); uint256 newRewardPerToken = stakingPool.rewardsPerTokenPoints.add(monaRewards .mul(1e18) .mul(pointMultiplier) .div(stakingPool.stakedMonaTotalForPool)) .sub(staker.lastRewardPoints); uint256 newRewards = staker.balance.mul(newRewardPerToken) .div(1e18) .div(pointMultiplier); // Figure out how much rewards are still pending uint256 secondsInCycle = stakingPool.daysInCycle.mul(SECONDS_IN_A_DAY); uint256 timeElapsedSinceStakingFromZero = _getNow().sub(staker.cycleStartTimestamp); uint256 startOfCurrentCycle = _getNow().sub(timeElapsedSinceStakingFromZero.mod(secondsInCycle)); if(startOfCurrentCycle > staker.lastRewardUpdateTime) { // We are in a new cycle // Bring over the pending rewards, they have been earned newRewards = newRewards.add(staker.monaRevenueRewardsEarned); newRewards = newRewards.sub(staker.monaRevenueRewardsReleased); // New cycle, the pending rewards from before move over newRewards = newRewards.add(staker.monaRevenueRewardsPending); uint256 monaPendingRewardsTotal = rewardsContract.MonaRevenueRewards(_poolId, startOfCurrentCycle, _getNow()); monaPendingRewardsTotal = monaPendingRewardsTotal.mul(1e18); pendingRewards = staker.balance.mul(monaPendingRewardsTotal); pendingRewards = pendingRewards.div(stakingPool.stakedMonaTotalForPool); // The pending rewards are now just what is in this cycle (calculation in case it overflows) pendingRewards = pendingRewards.div(1e18); claimableRewards = newRewards.sub(pendingRewards); } else { // We are in the same cycle, these new rewards calculated above are pending rewards. So no change to claimable rewards claimableRewards = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased); // The new rewards we calculated earlier are in the same cycle pendingRewards = newRewards.add(staker.monaRevenueRewardsPending); } } /* * @notice Returns the about of rewards yet to be claimed for bonuses (this currently includes pending and awarded together) * @param _poolId the id of the pool we are interested in * @param _user the user we are interested in * @dev returns the claimable rewards and pending rewards */ // TODO stack too deep function unclaimedBonusRewards( uint256 _poolId, address _user ) public view returns(uint256 claimableRewards, uint256 pendingRewards) { StakingPool storage stakingPool = pools[_poolId]; Staker storage staker = stakingPool.stakers[_user]; if (stakingPool.stakedMonaTotalForPool == 0 || !staker.isEarlyRewardsStaker) { return (0,0); } uint256 monaBonusRewards = rewardsContract.BonusMonaRevenueRewards(_poolId, stakingPool.lastUpdateTime, _getNow()); uint256 newBonusRewardPerToken = stakingPool.bonusRewardsPerTokenPoints; newBonusRewardPerToken = newBonusRewardPerToken.add(monaBonusRewards.mul(1e18).mul(pointMultiplier).div(stakingPool.earlyStakedMonaTotalForPool)); newBonusRewardPerToken = newBonusRewardPerToken.sub(staker.lastBonusRewardPoints); uint256 newBonusRewards = staker.balance.mul(newBonusRewardPerToken); newBonusRewards = newBonusRewards.div(1e18); newBonusRewards = newBonusRewards.div(pointMultiplier); // Figure out how much rewards are still pending uint256 secondsInCycle = stakingPool.daysInCycle.mul(SECONDS_IN_A_DAY); uint256 timeElapsedSinceStakingFromZero = _getNow().sub(staker.cycleStartTimestamp); uint256 startOfCurrentCycle = _getNow().sub(timeElapsedSinceStakingFromZero.mod(secondsInCycle)); if(startOfCurrentCycle > staker.lastRewardUpdateTime) { // We are in a new cycle // Bring over the pending rewards, they have been earned newBonusRewards = newBonusRewards.add(staker.bonusMonaRevenueRewardsPending); uint256 bonusMonaPendingRewardsTotal = 0; bonusMonaPendingRewardsTotal = rewardsContract.BonusMonaRevenueRewards(_poolId, startOfCurrentCycle, _getNow()); bonusMonaPendingRewardsTotal = bonusMonaPendingRewardsTotal.mul(1e18); uint256 bonusPendingRewards = staker.balance.mul(bonusMonaPendingRewardsTotal); bonusPendingRewards = bonusPendingRewards.div(stakingPool.earlyStakedMonaTotalForPool); // The pending rewards are now just what is in this cycle (calculation in case it overflows) bonusPendingRewards = bonusPendingRewards.div(1e18); uint256 bonusClaimable = newBonusRewards.sub(bonusPendingRewards); pendingRewards = bonusPendingRewards; claimableRewards = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased); claimableRewards = claimableRewards.add(bonusClaimable); } else { // We are in the same cycle, these new rewards calculated above are pending rewards. So no change to claimable rewards claimableRewards = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased); // The new rewards we calculated earlier are in the same cycle pendingRewards = newBonusRewards.add(staker.bonusMonaRevenueRewardsPending); } } /* * @notice Lets a user with rewards owing to claim tokens */ function claimReward(uint256 _poolId) external { _claimReward(_poolId, _msgSender()); } /** @notice Internal method for claimReward. */ function _claimReward( uint256 _poolId, address _user ) internal { require( tokensClaimable == true, "Tokens cannnot be claimed yet" ); updateReward(_poolId, _user); Staker storage staker = pools[_poolId].stakers[_user]; uint256 payableAmount = staker.monaRevenueRewardsEarned.sub(staker.monaRevenueRewardsReleased); staker.monaRevenueRewardsReleased = staker.monaRevenueRewardsReleased.add(payableAmount); /// @dev accounts for dust uint256 rewardBal = IERC20(monaToken).balanceOf(address(this)); if (payableAmount > rewardBal) { payableAmount = rewardBal; } IERC20(monaToken).transfer(_user, payableAmount); emit MonaRevenueRewardPaid(_user, payableAmount); } function getMonaTokenPerEthUnit(uint ethAmt) public view returns (uint liquidity){ return rewardsContract.getMonaPerEth(1e18); } function min(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a <= b ? a : b; } function _getNow() internal virtual view returns (uint256) { return block.timestamp; } /* ========== Recover ERC20 ========== */ /* * @notice allows for the recovery of incorrect ERC20 tokens sent to contract */ function reclaimERC20( address _tokenAddress, uint256 _tokenAmount ) external { // Cannot recover the staking token or the rewards token require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.reclaimERC20: Sender must be admin" ); require( _tokenAddress != address(monaToken), "DigitalaxMonaStaking.reclaimERC20: Cannot withdraw the rewards token" ); IERC20(_tokenAddress).transfer(_msgSender(), _tokenAmount); emit ReclaimedERC20(_tokenAddress, _tokenAmount); } /** * @notice EMERGENCY Recovers ETH, drains all ETH sitting on the smart contract * @dev Only access controls admin can access */ function reclaimETH(uint256 _amount) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMonaStaking.reclaimETH: Sender must be admin" ); _msgSender().transfer(address(this).balance); } }
Get the total ETH staked (all pools early stakers)/
function earlyStakedMonaInPool(uint256 _poolId) external view returns (uint256) { return pools[_poolId].earlyStakedMonaTotalForPool; }
12,801,892
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.9; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; /** * @title AggregateAccount * @notice AggregateAccount represents groups of assets * @dev Aggregate Account has to be set for Asset */ contract AggregateAccount is Initializable, OwnableUpgradeable { /// @notice name of the account. E.g BTC for aggregate account containing zBTC, BTC.e, ETH etc. string public accountName; /// @notice true if the assets represented by the aggregate are stablecoins /// @dev will be needed for interpool swapping bool public isStable; /** * @notice Initializer. * @param accountName_ The name of the aggregate account * @param isStable_ Tells if this aggregate holds stable assets or not */ function initialize(string memory accountName_, bool isStable_) external initializer { require(bytes(accountName_).length > 0, 'PLT:ACCOUNT_NAME_VOID'); __Ownable_init(); accountName = accountName_; isStable = isStable_; } /** * @notice Changes Account Name. Can only be set by the contract owner. * @param accountName_ the new name */ function setAccountName(string memory accountName_) external onlyOwner { require(bytes(accountName_).length > 0, 'Platypus: Aggregate account name cannot be zero'); accountName = accountName_; } }
Changes Account Name. Can only be set by the contract owner. accountName_ the new name/
function setAccountName(string memory accountName_) external onlyOwner { require(bytes(accountName_).length > 0, 'Platypus: Aggregate account name cannot be zero'); accountName = accountName_; }
1,035,708
/** * Spork Token Contracts * See Spork contract below for more detail. * * The DAO and Spork is free software: you can redistribute it and/or modify * it under the terms of the GNU lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The DAO and Spork 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 lesser General Public License for more details. * * http://www.gnu.org/licenses/ * * credit * The DAO, Slock.it, Ethereum Foundation, EthCore, Consensys, pseudonymous * rebels everywhere, and every lunch spot with proper eating utensils. ? */ /** * @title TokenInterface * @notice ERC 20 token standard and DAO token interface. */ contract TokenInterface { event Transfer( address indexed _from, address indexed _to, uint256 _amount); event Approval( address indexed _owner, address indexed _spender, uint256 _amount); mapping (address => // owner uint256) balances; mapping (address => // owner mapping (address => // spender uint256)) allowed; uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _amount) returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) returns (bool success); function approve(address _spender, uint256 _amount) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } /** * @title Spork * * @notice A rogue upgrade token for The DAO. There is nothing safe about this * contract or this life so strap in, bitches. You are responsible for you. * A Spork is minted through burning DAO tokens. This is irreversible and for * entertainment purposes. So why would you do this? Do it for love, do it * for So Tokey Nada Mojito, do it for the lulz; just do it with conviction! * * usage * 1. Use The DAO to grant an allowance of DAO for the Spork contract. * + `DAO.approve(spork_contract_address, amount_of_DAO_to_burn)` * + Only grant the amount of DAO you are ready to destroy forever. * 2. Use the Spork mint function to ... * 1. Burn an amount of DAO up to the amount approved in the previous step. * 2. Mint an equivalent amount of Spork. * 3. Assign Spork tokens to the sender account. * 3. You now have Sporks. Dig in! */ contract Spork is TokenInterface { // crash and burn address constant TheDAO = 0xbb9bc244d798123fde783fcc1c72d3bb8c189413; event Mint( address indexed _sender, uint256 indexed _amount, string _lulz); // vanity attributes string public name = "Spork"; string public symbol = "SPRK"; string public version = "Spork:0.1"; uint8 public decimals = 0; // @see {Spork.mint} function () { throw; // this is a coin, not a wallet. } /** * @notice Burn DAO tokens in exchange for Spork tokens * @param _amount Amount of DAO to burn and equivalent Spork to mint * @param _lulz If you gotta go, go with a smile! ? * @return Determine if request was successful */ function mint(uint256 _amount, string _lulz) returns (bool success) { if (totalSupply + _amount <= totalSupply) return false; // zero or rollover value if (!TokenInterface(TheDAO).transferFrom(msg.sender, this, _amount)) return false; // unable to retrieve DAO tokens for sender balances[msg.sender] += _amount; totalSupply += _amount; Mint(msg.sender, _amount, _lulz); return true; } /** * @notice Transfer Spork tokens from `msg.sender` to another account. * @param _to Account receiving tokens * @param _amount Amount of tokens to transfer * @return Determine if request was successful */ function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[_to] + _amount <= balances[_to]) return false; // zero or rollover value if (balances[msg.sender] < _amount) return false; // party foul, sender does not have enough sporks balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } /** * @notice Transfer Spork tokens from one account to another * @param _from Account holding tokens for which `msg.sender` is an approved * spender with an allowance of at least `_amount` tokens * @param _to Account receiving tokens * @param _amount Amount of tokens to transfer * @return Determine if request was successful */ function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { if (balances[_to] + _amount <= balances[_to]) return false; // zero or rollover value if (allowed[_from][msg.sender] < _amount) return false; // sender does not have enough allowance if (balances[msg.sender] < _amount) return false; // party foul, sender does not have enough sporks balances[_to] += _amount; balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; Transfer(_from, _to, _amount); return true; } /** * @notice Determine the Spork token balance for an account * @param _owner Account holding tokens * @return Token balance */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /** * @notice Approve an address to spend tokens on your behalf * @param _spender Account to spend tokens on behalf of `msg.sender` * @param _amount Maximum amount `_spender` can transfer from `msg.sender` * @return Determine if request was successful */ function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * @notice Maximum amount a spender can withdraw from an account * @param _owner The account holding tokens * @param _spender The account spending tokens * @return Remaining allowance `_spender` can withdraw from `_owner` */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
Determine the Spork token balance for an account _owner Account holding tokens return Token balance/
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
12,636,392
//Address: 0x83a326995d1f988b62b487f2838501d9fbfdd23e //Contract name: PreSalePTARK //Balance: 0 Ether //Verification Date: 2/9/2018 //Transacion Count: 4 // CODE STARTS HERE // Tarka Pre-Sale token smart contract. // Developed by Phenom.Team <[email protected]> pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns(uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal constant returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract PreSalePTARK { using SafeMath for uint256; //Owner address address public owner; //Public variables of the token string public name = "Tarka Pre-Sale Token"; string public symbol = "PTARK"; uint8 public decimals = 18; uint256 public totalSupply = 0; mapping (address => uint256) public balances; // Events Log event Transfer(address _from, address _to, uint256 amount); event Burned(address _from, uint256 amount); // Modifiers // Allows execution by the contract owner only modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Contract constructor function sets owner address */ function PreSalePTARK() { owner = msg.sender; } /** * @dev Allows owner to transfer ownership of contract * @param _newOwner newOwner address */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0)); owner = _newOwner; } /** * @dev Get balance of investor * @param _investor investor's address * @return balance of investor */ function balanceOf(address _investor) public constant returns(uint256) { return balances[_investor]; } /** * @dev Mint tokens * @param _investor beneficiary address the tokens will be issued to * @param _mintedAmount number of tokens to issue */ function mintTokens(address _investor, uint256 _mintedAmount) external onlyOwner { require(_mintedAmount > 0); balances[_investor] = balances[_investor].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(this, _investor, _mintedAmount); } /** * @dev Burn Tokens * @param _investor token holder address which the tokens will be burnt */ function burnTokens(address _investor) external onlyOwner { require(balances[_investor] > 0); uint256 tokens = balances[_investor]; balances[_investor] = 0; totalSupply = totalSupply.sub(tokens); Burned(_investor, tokens); } }
Contract constructor function sets owner address/
function PreSalePTARK() { owner = msg.sender; }
2,506,002
// SPDX-License-Identifier: MIT // Insulin calculator storage. Platinum devTeam. pragma solidity ^0.8.6; contract EventStorage { struct Insulin { string insulinType; uint256 duration; } string public version; Insulin[] public INSULINS; // Insulin[2] public INSULINS = [ // Insulin('Novorapid', 180 ), // Insulin('Humuline', 300 ) // ]; mapping(address => Insulin[]) internal personalInsulins; event MeasureRecord ( address indexed sender, uint256 timestamp, //Unix timestamp uint256 glucose, //Current blood glucose reading uint256 carbs, //Estimated carbohydrate intake uint256 units, //Units of insulin the app has calculated for you Insulin insulinType // lookup table with insulin name (string) and duration in minutes ); constructor (string memory _version) { version = _version; INSULINS.push(Insulin('Novorapid', 180 )); INSULINS.push(Insulin('Humuline', 300 )); } function bolus ( uint256 _timestamp, //Unix timestamp uint256 _glucose, //Current blood glucose reading uint256 _carbs, //Estimated carbohydrate intake uint256 _units, //Units of insulin the app has calculated for you uint256 _insulinIndex // index from lookup table with insulin name (string) and duration in seconds ) external { require(_timestamp > 0, "Cant be zero"); //TODO //add more checks if need like above; if (personalInsulins[msg.sender].length == 0) { emit MeasureRecord ( msg.sender, _timestamp, _glucose, _carbs, _units, INSULINS[_insulinIndex] ); } else { emit MeasureRecord ( msg.sender, _timestamp, _glucose, _carbs, _units, personalInsulins[msg.sender][_insulinIndex] ); } } function addInsulin(string memory _insulin, uint256 _seconds) external { Insulin[] storage ins = personalInsulins[msg.sender]; ins.push(Insulin(_insulin, _seconds)); } function removeInsulin(uint256 _id) external { Insulin[] memory insOld = personalInsulins[msg.sender]; //We need recreate all array due https://docs.soliditylang.org/en/v0.8.6/types.html#delete delete personalInsulins[msg.sender]; for (uint256 i = 0; i < insOld.length; i++) { if (i != _id) { personalInsulins[msg.sender].push(insOld[i]); } } } function getInsulins(address _user) public view returns (Insulin[] memory insulins) { if (personalInsulins[msg.sender].length == 0) { return INSULINS; } else { return personalInsulins[msg.sender]; } } // function getPersonalInsulins(address user) public view returns(string[] memory persIns) { // return personalInsulins[user]; // } // function getAllInsulins() public view returns (string[] memory allIns) { // uint256 allArraysLength = INSULINS.length + personalInsulins[msg.sender].length; // //Due https://docs.soliditylang.org/en/v0.8.6/types.html#allocating-memory-arrays // string[] memory result = new string[](allArraysLength); // for (uint256 i = 0; i < INSULINS.length; i++) { // result[i] = INSULINS[i]; // } // //add spersonal array // for (uint256 i = 0; i < personalInsulins[msg.sender].length; i++) { // result[i + INSULINS.length] = personalInsulins[msg.sender][i]; // } // return result; // } }
We need recreate all array due https:docs.soliditylang.org/en/v0.8.6/types.htmldelete
function removeInsulin(uint256 _id) external { Insulin[] memory insOld = personalInsulins[msg.sender]; delete personalInsulins[msg.sender]; for (uint256 i = 0; i < insOld.length; i++) { if (i != _id) { personalInsulins[msg.sender].push(insOld[i]); } } }
6,392,889
./full_match/80001/0xd1E00A34C819e7f2DA2F8715E2c66b5Bc6677E3c/sources/deploy/contracts/core/interfaces/IFinder.sol
Provides addresses of the contracts implementing certain interfaces./
interface ISynthereumFinder { function changeImplementationAddress( bytes32 interfaceName, address implementationAddress ) external; function getImplementationAddress(bytes32 interfaceName) external view returns (address); pragma solidity >=0.8.0; }
9,459,986
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import { MerkleTreeLib as Merkle } from "./merkle/MerkleTreeLib.sol"; library TransactionsLib { enum TransactionType { HARD_CREATE, HARD_DEPOSIT, HARD_WITHDRAW, HARD_ADD_SIGNER, SOFT_WITHDRAW, SOFT_CREATE, SOFT_TRANSFER, SOFT_CHANGE_SIGNER } struct TransactionsMetadata { uint16 hardCreateCount; uint16 hardDepositCount; uint16 hardWithdrawCount; uint16 hardAddSignerCount; uint16 softWithdrawCount; uint16 softCreateCount; uint16 softTransferCount; uint16 softChangeSignerCount; } struct HardCreate { uint40 hardTransactionIndex; uint32 accountIndex; uint56 value; address contractAddress; address signerAddress; bytes32 intermediateStateRoot; } struct HardDeposit { uint40 hardTransactionIndex; uint32 accountIndex; uint56 value; bytes32 intermediateStateRoot; } struct HardWithdrawal { uint40 hardTransactionIndex; uint32 accountIndex; address withdrawalAddress; uint56 value; bytes32 intermediateStateRoot; } struct HardAddSigner { uint40 hardTransactionIndex; uint32 accountIndex; address signingAddress; bytes32 intermediateStateRoot; } struct SoftWithdrawal { uint24 nonce; uint32 accountIndex; address withdrawalAddress; uint56 value; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; } struct SoftCreate { uint24 nonce; uint32 fromIndex; uint32 toIndex; uint56 value; address contractAddress; address signingAddress; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; } struct SoftTransfer { uint24 nonce; uint32 fromIndex; uint32 toIndex; uint56 value; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; } struct SoftChangeSigner { uint24 nonce; uint32 fromIndex; address signingAddress; uint8 modificationCategory; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; } function decodeTransactionsMetadata(bytes memory input) internal pure returns (TransactionsMetadata memory) { uint16 hardCreateCount; uint16 hardDepositCount; uint16 hardWithdrawCount; uint16 hardAddSignerCount; uint16 softWithdrawCount; uint16 softCreateCount; uint16 softTransferCount; uint16 softChangeSignerCount; assembly { // Add 32 to skip length let ptr := add(input, 32) hardCreateCount := shr(240, mload(ptr)) hardDepositCount := shr(240, mload(add(ptr, 2))) hardWithdrawCount := shr(240, mload(add(ptr, 4))) hardAddSignerCount := shr(240, mload(add(ptr, 6))) softWithdrawCount := shr(240, mload(add(ptr, 8))) softCreateCount := shr(240, mload(add(ptr, 10))) softTransferCount := shr(240, mload(add(ptr, 12))) softChangeSignerCount := shr(240, mload(add(ptr, 14))) } return TransactionsMetadata( hardCreateCount, hardDepositCount, hardWithdrawCount, hardAddSignerCount, softWithdrawCount, softCreateCount, softTransferCount, softChangeSignerCount ); } function decodeHardCreate(bytes memory input) internal pure returns (HardCreate memory) { uint40 hardTransactionIndex; uint32 accountIndex; uint56 value; address contractAddress; address signerAddress; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) hardTransactionIndex := shr(216, mload(ptr)) accountIndex := shr(224, mload(add(ptr, 5))) value := shr(200, mload(add(ptr, 9))) contractAddress := shr(96, mload(add(ptr, 16))) signerAddress := shr(96, mload(add(ptr, 36))) intermediateStateRoot := mload(add(ptr, 56)) } return HardCreate( hardTransactionIndex, accountIndex, value, contractAddress, signerAddress, intermediateStateRoot ); } function decodeHardDeposit(bytes memory input) internal pure returns (HardDeposit memory) { uint40 hardTransactionIndex; uint32 accountIndex; uint56 value; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) hardTransactionIndex := shr(216, mload(ptr)) accountIndex := shr(224, mload(add(ptr, 5))) value := shr(200, mload(add(ptr, 9))) intermediateStateRoot := mload(add(ptr, 16)) } return HardDeposit( hardTransactionIndex, accountIndex, value, intermediateStateRoot ); } function decodeHardWithdrawal(bytes memory input) internal pure returns (HardWithdrawal memory) { uint40 hardTransactionIndex; uint32 accountIndex; address withdrawalAddress; uint56 value; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) hardTransactionIndex := shr(216, mload(ptr)) accountIndex := shr(224, mload(add(ptr, 5))) withdrawalAddress := shr(96, mload(add(ptr, 9))) value := shr(200, mload(add(ptr, 29))) intermediateStateRoot := mload(add(ptr, 36)) } return HardWithdrawal( hardTransactionIndex, accountIndex, withdrawalAddress, value, intermediateStateRoot ); } function decodeHardAddSigner(bytes memory input) internal pure returns (HardAddSigner memory) { uint40 hardTransactionIndex; uint32 accountIndex; address signingAddress; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) hardTransactionIndex := shr(216, mload(ptr)) accountIndex := shr(224, mload(add(ptr, 5))) signingAddress := shr(96, mload(add(ptr, 9))) intermediateStateRoot := mload(add(ptr, 29)) } return HardAddSigner( hardTransactionIndex, accountIndex, signingAddress, intermediateStateRoot ); } function decodeSoftWithdrawal(bytes memory input) internal pure returns (SoftWithdrawal memory) { uint24 nonce; uint32 accountIndex; address withdrawalAddress; uint56 value; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) nonce := shr(232, mload(ptr)) accountIndex := shr(224, mload(add(ptr, 3))) withdrawalAddress := shr(96, mload(add(ptr, 7))) value := shr(200, mload(add(ptr, 27))) sigV := shr(248, mload(add(ptr, 34))) sigR := mload(add(ptr, 35)) sigS := mload(add(ptr, 67)) intermediateStateRoot := mload(add(ptr, 99)) } return SoftWithdrawal( nonce, accountIndex, withdrawalAddress, value, sigV, sigR, sigS, intermediateStateRoot ); } function decodeSoftCreate(bytes memory input) internal pure returns (SoftCreate memory) { uint24 nonce; uint32 fromIndex; uint32 toIndex; uint56 value; address contractAddress; address signingAddress; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) nonce := shr(232, mload(ptr)) fromIndex := shr(224, mload(add(ptr, 3))) toIndex := shr(224, mload(add(ptr, 7))) value := shr(200, mload(add(ptr, 11))) contractAddress := shr(96, mload(add(ptr, 18))) signingAddress := shr(96, mload(add(ptr, 38))) sigV := shr(248, mload(add(ptr, 58))) sigR := mload(add(ptr, 59)) sigS := mload(add(ptr, 91)) intermediateStateRoot := mload(add(ptr, 123)) } return SoftCreate( nonce, fromIndex, toIndex, value, contractAddress, signingAddress, sigV, sigR, sigS, intermediateStateRoot ); } function decodeSoftTransfer(bytes memory input) internal pure returns (SoftTransfer memory) { uint24 nonce; uint32 fromIndex; uint32 toIndex; uint56 value; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) nonce := shr(232, mload(ptr)) fromIndex := shr(224, mload(add(ptr, 3))) toIndex := shr(224, mload(add(ptr, 7))) value := shr(200, mload(add(ptr, 11))) sigV := shr(248, mload(add(ptr, 18))) sigR := mload(add(ptr, 19)) sigS := mload(add(ptr, 51)) intermediateStateRoot := mload(add(ptr, 83)) } return SoftTransfer( nonce, fromIndex, toIndex, value, sigV, sigR, sigS, intermediateStateRoot ); } function decodeSoftChangeSigner(bytes memory input) internal pure returns (SoftChangeSigner memory) { uint24 nonce; uint32 fromIndex; address signingAddress; uint8 modificationCategory; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; assembly { // Add 33 to skip length and prefix let ptr := add(input, 33) nonce := shr(232, mload(ptr)) fromIndex := shr(224, mload(add(ptr, 3))) signingAddress := shr(96, mload(add(ptr, 7))) modificationCategory := shr(248, mload(add(ptr, 27))) sigV := shr(248, mload(add(ptr, 28))) sigR := mload(add(ptr, 29)) sigS := mload(add(ptr, 61)) intermediateStateRoot := mload(add(ptr, 93)) } return SoftChangeSigner( nonce, fromIndex, signingAddress, modificationCategory, sigV, sigR, sigS, intermediateStateRoot ); } /** * @dev stateRootFromTransaction * Reads the state root from a transaction by peeling off the last 32 bytes. * @param transaction - encoded transaction of any type * @return root - state root from the transaction */ function stateRootFromTransaction( bytes memory transaction ) internal pure returns (bytes32 root) { assembly { let inPtr := add(transaction, 32) let len := mload(transaction) let rootPtr := add(inPtr, sub(len, 32)) root := mload(rootPtr) } } /** * @dev transactionPrefix * Returns the transaction prefix from an encoded transaction by reading the first byte. * @param transaction - encoded transaction of any type * @return prefix - transaction prefix read from the first byte of the transaction */ function transactionPrefix( bytes memory transaction ) internal pure returns (uint8 prefix) { assembly { prefix := shr(248, mload(add(transaction, 32))) } } /** * @dev transactionsCount * Returns the total number of transactions in the tx metadata. * @param meta - transactions metadata from a transaction buffer * @return number of transactions the metadata says exist in the buffer */ function transactionsCount( TransactionsMetadata memory meta ) internal pure returns (uint256) { return ( meta.hardCreateCount + meta.hardDepositCount + meta.hardWithdrawCount + meta.hardAddSignerCount + meta.softWithdrawCount + meta.softCreateCount + meta.softTransferCount + meta.softChangeSignerCount ); } /** * @dev expectedTransactionsLength * Calculates the expected size of the transactions buffer based on the transactions metadata. * @param meta - transactions metadata from a transaction buffer * @return number of bytes the transactions buffer should have */ function expectedTransactionsLength( TransactionsMetadata memory meta ) internal pure returns (uint256) { return ( meta.hardCreateCount * 88 + meta.hardDepositCount * 48 + meta.hardWithdrawCount * 68 + meta.hardAddSignerCount * 61 + meta.softWithdrawCount * 131 + meta.softCreateCount * 155 + meta.softTransferCount * 115 + meta.softChangeSignerCount * 125 ); } function putLeaves( bytes[] memory leaves, bool identitySuccess, uint256 leafIndex, uint256 currentPointer, uint8 typePrefix, uint256 typeCount, uint256 typeSize ) internal view returns ( bool _identitySuccess, uint256 _leafIndex, uint256 _currentPointer ) { for (uint256 i = 0; i < typeCount; i++) { bytes memory _tx = new bytes(typeSize + 1); assembly { let outPtr := add(_tx, 32) mstore8(outPtr, typePrefix) outPtr := add(outPtr, 1) identitySuccess := and( identitySuccess, staticcall(gas(), 0x04, currentPointer, typeSize, outPtr, typeSize) ) currentPointer := add(currentPointer, typeSize) } leaves[leafIndex++] = _tx; } return (identitySuccess, leafIndex, currentPointer); } function deriveTransactionsRoot( bytes memory transactionsData ) internal view returns (bytes32) { TransactionsMetadata memory meta = decodeTransactionsMetadata( transactionsData ); uint256 expectedLength = expectedTransactionsLength(meta); /* If the transactions data size is incommensurate with the transactions header, the block is erroneous. */ require( transactionsData.length == expectedLength + 16, "Incorrect transactions data buffer length." ); uint256 txCount = transactionsCount(meta); uint256 txPtr; uint256 leafIndex = 0; assembly { txPtr := add(transactionsData, 48) } bool identitySuccess = true; bytes[] memory leaves = new bytes[](txCount); uint16[2][8] memory elements = [ [meta.hardCreateCount, 88], [meta.hardDepositCount, 48], [meta.hardWithdrawCount, 68], [meta.hardAddSignerCount, 61], [meta.softWithdrawCount, 131], [meta.softCreateCount, 155], [meta.softTransferCount, 115], [meta.softChangeSignerCount, 125] ]; for (uint8 i = 0; i < 8; i++) { uint16 count = elements[i][0]; if (count > 0) { (identitySuccess, leafIndex, txPtr) = putLeaves( leaves, identitySuccess, leafIndex, txPtr, i, count, elements[i][1] ); } } require(identitySuccess, "Failed to copy bytes."); return Merkle.getMerkleRoot(leaves); } function recoverSignature(bytes memory txData) internal pure returns (address signer) { bytes32 msgHash; uint8 v; bytes32 r; bytes32 s; uint8 prefix = transactionPrefix(txData); require(prefix >= 4, "Input not a soft transaction."); if (prefix == 5) { // Hard creates use a null buffer for the `toIndex` assembly { let mask := 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff let ptr := add(txData, 0x28) let data := mload(ptr) mstore(ptr, and(data, mask)) } } assembly { let ptr := add(txData, 0x20) let inputLen := sub(mload(txData), 97) msgHash := keccak256(ptr, inputLen) let rOffset := add(ptr, inputLen) r := mload(rOffset) s := mload(add(rOffset, 32)) v := shr(248, mload(add(rOffset, 64))) } signer = ecrecover(msgHash, v, r, s); } }
Add 33 to skip length and prefix
function decodeSoftTransfer(bytes memory input) internal pure returns (SoftTransfer memory) { uint24 nonce; uint32 fromIndex; uint32 toIndex; uint56 value; uint8 sigV; bytes32 sigR; bytes32 sigS; bytes32 intermediateStateRoot; assembly { let ptr := add(input, 33) nonce := shr(232, mload(ptr)) fromIndex := shr(224, mload(add(ptr, 3))) toIndex := shr(224, mload(add(ptr, 7))) value := shr(200, mload(add(ptr, 11))) sigV := shr(248, mload(add(ptr, 18))) sigR := mload(add(ptr, 19)) sigS := mload(add(ptr, 51)) intermediateStateRoot := mload(add(ptr, 83)) } return SoftTransfer( nonce, fromIndex, toIndex, value, sigV, sigR, sigS, intermediateStateRoot ); }
5,452,367
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "../interfaces/IOracle.sol"; // Chainlink Aggregator interface IAggregator { function latestAnswer() external view returns (int256 answer); } contract USTOracle is IOracle { IAggregator constant public UST = IAggregator(0x8b6d9085f310396C6E4f0012783E9f850eaa8a82); // Calculates the lastest exchange rate // Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD function _get() internal view returns (uint256) { uint256 ustPrice = uint256(UST.latestAnswer()); return 1e26 / ustPrice; } // Get the latest exchange rate /// @inheritdoc IOracle function get(bytes calldata) public view override returns (bool, uint256) { return (true, _get()); } // Check the last exchange rate without any state changes /// @inheritdoc IOracle function peek(bytes calldata) public view override returns (bool, uint256) { return (true, _get()); } // Check the current spot exchange rate without any state changes /// @inheritdoc IOracle function peekSpot(bytes calldata data) external view override returns (uint256 rate) { (, rate) = peek(data); } /// @inheritdoc IOracle function name(bytes calldata) public pure override returns (string memory) { return "Chainlink UST"; } /// @inheritdoc IOracle function symbol(bytes calldata) public pure override returns (string memory) { return "LINK/UST"; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.6.12; interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); }
@inheritdoc IOracle
function symbol(bytes calldata) public pure override returns (string memory) { return "LINK/UST"; }
5,756,732
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/Marketplace.sol
Changes Presale Sale Max For Sale/
function __ChangePresaleSaleMaxForSale(uint SaleIndex, uint MaxForSale) external onlyAdmin { require(PresaleSalesInternal[SaleIndex]._Active, "Marketplace: Sale Not Active"); PresaleSales[SaleIndex]._MaxForSale = MaxForSale; }
8,471,301
//Address: 0xae4f56f072c34c0a65b3ae3e4db797d831439d93 //Contract name: Gimli //Balance: 0 Ether //Verification Date: 9/16/2017 //Transacion Count: 2713 // CODE STARTS HERE pragma solidity ^0.4.11; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool success); function approve(address spender, uint256 value) returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner() { require(msg.sender == owner); _; } function Ownable() { owner = msg.sender; } /// @notice Transfer ownership from `owner` to `newOwner` /// @param _newOwner The new contract owner function transferOwnership(address _newOwner) onlyOwner { if (_newOwner != address(0)) { newOwner = _newOwner; } } /// @notice accept ownership of the contract function acceptOwnership() { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Administrable is Ownable { event AdminstratorAdded(address adminAddress); event AdminstratorRemoved(address adminAddress); mapping (address => bool) public administrators; modifier onlyAdministrator() { require(administrators[msg.sender] || owner == msg.sender); // owner is an admin by default _; } /// @notice Add an administrator /// @param _adminAddress The new administrator address function addAdministrators(address _adminAddress) onlyOwner { administrators[_adminAddress] = true; AdminstratorAdded(_adminAddress); } /// @notice Remove an administrator /// @param _adminAddress The administrator address to remove function removeAdministrators(address _adminAddress) onlyOwner { delete administrators[_adminAddress]; AdminstratorRemoved(_adminAddress); } } /// @title Gimli Token Contract. contract GimliToken is ERC20, SafeMath, Ownable { /************************* **** Global variables **** *************************/ uint8 public constant decimals = 8; string public constant name = "Gimli Token"; string public constant symbol = "GIM"; string public constant version = 'v1'; /// total amount of tokens uint256 public constant UNIT = 10**uint256(decimals); uint256 constant MILLION_GML = 10**6 * UNIT; // can't use `safeMul` with constant /// Should include CROWDSALE_AMOUNT and VESTING_X_AMOUNT uint256 public constant TOTAL_SUPPLY = 150 * MILLION_GML; // can't use `safeMul` with constant; /// balances indexed by address mapping (address => uint256) balances; /// allowances indexed by owner and spender mapping (address => mapping (address => uint256)) allowed; bool public transferable = false; /********************* **** Transactions **** *********************/ /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) { require(transferable); require(balances[msg.sender] >= _value && _value >=0); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(transferable); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value >= 0); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /**************** **** Getters **** ****************/ /// @notice Get balance of an address /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /// @notice Get tokens allowed to spent by `_spender` /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /// @title Gimli Crowdsale Contract. contract GimliCrowdsale is SafeMath, GimliToken { address public constant MULTISIG_WALLET_ADDRESS = 0xc79ab28c5c03f1e7fbef056167364e6782f9ff4f; address public constant LOCKED_ADDRESS = 0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD; // crowdsale uint256 public constant CROWDSALE_AMOUNT = 80 * MILLION_GML; // Should not include vested amount uint256 public constant START_DATE = 1505736000; // (epoch timestamp) uint256 public constant END_DATE = 1508500800; // TODO (epoch timestamp) uint256 public constant CROWDSALE_PRICE = 700; // 700 GML / ETH uint256 public constant VESTING_1_AMOUNT = 10 * MILLION_GML; // GIM reserve fund uint256 public constant VESTING_1_DATE = 1537272000; // TODO (epoch timestamp) uint256 public constant VESTING_2_AMOUNT = 30 * MILLION_GML; // Team uint256 public constant VESTING_2_DATE = 1568808000; // TODO (epoch timestamp) bool public vesting1Withdrawn = false; bool public vesting2Withdrawn = false; bool public crowdsaleCanceled = false; uint256 public soldAmount; // GIM uint256 public paidAmount; // ETH /// @notice `msg.sender` invest `msg.value` function() payable { require(!crowdsaleCanceled); require(msg.value > 0); // check date require(block.timestamp >= START_DATE && block.timestamp <= END_DATE); // calculate and check quantity uint256 quantity = safeDiv(safeMul(msg.value, CROWDSALE_PRICE), 10**(18-uint256(decimals))); require(safeSub(balances[this], quantity) >= 0); require(MULTISIG_WALLET_ADDRESS.send(msg.value)); // update balances balances[this] = safeSub(balances[this], quantity); balances[msg.sender] = safeAdd(balances[msg.sender], quantity); soldAmount = safeAdd(soldAmount, quantity); paidAmount = safeAdd(paidAmount, msg.value); Transfer(this, msg.sender, quantity); } /// @notice returns non-sold tokens to owner function closeCrowdsale() onlyOwner { // check if closable require(block.timestamp > END_DATE || crowdsaleCanceled || balances[this] == 0); // enable token transfer transferable = true; // update balances if (balances[this] > 0) { uint256 amount = balances[this]; balances[MULTISIG_WALLET_ADDRESS] = safeAdd(balances[MULTISIG_WALLET_ADDRESS], amount); balances[this] = 0; Transfer(this, MULTISIG_WALLET_ADDRESS, amount); } } /// @notice Terminate the crowdsale before END_DATE function cancelCrowdsale() onlyOwner { crowdsaleCanceled = true; } /// @notice Pre-allocate tokens to advisor or partner /// @param _to The pre-allocation destination /// @param _value The amount of token to be allocated /// @param _price ETH paid for these tokens function preAllocate(address _to, uint256 _value, uint256 _price) onlyOwner { require(block.timestamp < START_DATE); balances[this] = safeSub(balances[this], _value); balances[_to] = safeAdd(balances[_to], _value); soldAmount = safeAdd(soldAmount, _value); paidAmount = safeAdd(paidAmount, _price); Transfer(this, _to, _value); } /// @notice Send vested amount to _destination /// @param _destination The address of the recipient /// @return Whether the release was successful or not function releaseVesting(address _destination) onlyOwner returns (bool success) { if (block.timestamp > VESTING_1_DATE && vesting1Withdrawn == false) { balances[LOCKED_ADDRESS] = safeSub(balances[LOCKED_ADDRESS], VESTING_1_AMOUNT); balances[_destination] = safeAdd(balances[_destination], VESTING_1_AMOUNT); vesting1Withdrawn = true; Transfer(LOCKED_ADDRESS, _destination, VESTING_1_AMOUNT); return true; } if (block.timestamp > VESTING_2_DATE && vesting2Withdrawn == false) { balances[LOCKED_ADDRESS] = safeSub(balances[LOCKED_ADDRESS], VESTING_2_AMOUNT); balances[_destination] = safeAdd(balances[_destination], VESTING_2_AMOUNT); vesting2Withdrawn = true; Transfer(LOCKED_ADDRESS, _destination, VESTING_2_AMOUNT); return true; } return false; } /// @notice transfer out any accidentally sent ERC20 tokens /// @param tokenAddress Address of the ERC20 contract /// @param amount The amount of token to be transfered function transferOtherERC20Token(address tokenAddress, uint256 amount) onlyOwner returns (bool success) { // can't be used for GIM token require(tokenAddress != address(this) || transferable); return ERC20(tokenAddress).transfer(owner, amount); } } /// @title Main Gimli contract. contract Gimli is GimliCrowdsale, Administrable { address public streamerContract; uint256 public streamerContractMaxAmount; event StreamerContractChanged(address newContractAddress, uint256 newMaxAmount); /// @notice Gimli Contract constructor. `msg.sender` is the owner. function Gimli() { // Give the multisig wallet initial tokens balances[MULTISIG_WALLET_ADDRESS] = safeAdd(balances[MULTISIG_WALLET_ADDRESS], TOTAL_SUPPLY - CROWDSALE_AMOUNT - VESTING_1_AMOUNT - VESTING_2_AMOUNT); // Give the contract crowdsale amount balances[this] = CROWDSALE_AMOUNT; // Locked address balances[LOCKED_ADDRESS] = VESTING_1_AMOUNT + VESTING_2_AMOUNT; // For ERC20 compatibility totalSupply = TOTAL_SUPPLY; } /// @notice authorize an address to transfer GIM on behalf an user /// @param _contractAddress Address of GimliStreamer contract /// @param _maxAmount The maximum amount that can be transfered by the contract function setStreamerContract( address _contractAddress, uint256 _maxAmount) onlyAdministrator { // To change the maximum amount you first have to reduce it to 0` require(_maxAmount == 0 || streamerContractMaxAmount == 0); streamerContract = _contractAddress; streamerContractMaxAmount = _maxAmount; StreamerContractChanged(streamerContract, streamerContractMaxAmount); } /// @notice Called by a Gimli contract to transfer GIM /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _amount The amount of token to be transferred /// @return Whether the transfer was successful or not function transferGIM(address _from, address _to, uint256 _amount) returns (bool success) { require(msg.sender == streamerContract); require(tx.origin == _from); require(_amount <= streamerContractMaxAmount); if (balances[_from] < _amount || _amount <= 0) return false; balances[_from] = safeSub(balances[_from], _amount); balances[_to] = safeAdd(balances[_to], _amount); Transfer(_from, _to, _amount); return true; } }
Send vested amount to _destination _destination The address of the recipient return Whether the release was successful or not
function releaseVesting(address _destination) onlyOwner returns (bool success) { if (block.timestamp > VESTING_1_DATE && vesting1Withdrawn == false) { balances[LOCKED_ADDRESS] = safeSub(balances[LOCKED_ADDRESS], VESTING_1_AMOUNT); balances[_destination] = safeAdd(balances[_destination], VESTING_1_AMOUNT); vesting1Withdrawn = true; Transfer(LOCKED_ADDRESS, _destination, VESTING_1_AMOUNT); return true; } if (block.timestamp > VESTING_2_DATE && vesting2Withdrawn == false) { balances[LOCKED_ADDRESS] = safeSub(balances[LOCKED_ADDRESS], VESTING_2_AMOUNT); balances[_destination] = safeAdd(balances[_destination], VESTING_2_AMOUNT); vesting2Withdrawn = true; Transfer(LOCKED_ADDRESS, _destination, VESTING_2_AMOUNT); return true; } return false; }
15,819,795
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import '../utils/OwnableUpgradeable.sol'; import './OmnuumNFT1155.sol'; /// @title OmnuumMintManager - Manage mint data and logics except ticket minting /// @author Omnuum Dev Team - <[email protected]> /// @notice Use only purpose for Omnuum contract OmnuumMintManager is OwnableUpgradeable { uint8 public constant rateDecimal = 5; /// @notice minting fee rate uint256 public feeRate; /// @notice minimum fee (ether) uint256 public minFee; /// @notice special fee rates for exceptional contracts mapping(address => uint256) public specialFeeRates; /// @notice nft => groupId => PublicMintSchedule mapping(address => mapping(uint256 => PublicMintSchedule)) public publicMintSchedules; event ChangeFeeRate(uint256 feeRate); event SetSpecialFeeRate(address indexed nftContract, uint256 discountFeeRate); event SetMinFee(uint256 minFee); event Airdrop(address indexed nftContract, address indexed receiver, uint256 quantity); event SetPublicSchedule( address indexed nftContract, uint256 indexed groupId, uint256 endDate, uint256 basePrice, uint32 supply, uint32 maxMintAtAddress ); event PublicMint( address indexed nftContract, address indexed minter, uint256 indexed groupId, uint32 quantity, uint32 maxQuantity, uint256 price ); struct PublicMintSchedule { uint32 supply; // max possible minting amount uint32 mintedTotal; // total minted amount uint32 maxMintAtAddress; // max possible minting amount per address mapping(address => uint32) minted; // minting count per address uint256 endDate; // minting schedule end date timestamp uint256 basePrice; // minting price } function initialize(uint256 _feeRate) public initializer { __Ownable_init(); feeRate = _feeRate; minFee = 0.0005 ether; } /// @notice get fee rate of given nft contract /// @param _nftContract address of nft contract function getFeeRate(address _nftContract) public view returns (uint256) { return specialFeeRates[_nftContract] == 0 ? feeRate : specialFeeRates[_nftContract]; } /// @notice change fee rate /// @param _newFeeRate new fee rate function changeFeeRate(uint256 _newFeeRate) external onlyOwner { /// @custom:error (NE1) - Fee rate should be lower than 100% require(_newFeeRate <= 100000, 'NE1'); feeRate = _newFeeRate; emit ChangeFeeRate(_newFeeRate); } /// @notice set special fee rate for exceptional case /// @param _nftContract address of nft /// @param _feeRate fee rate only for nft contract function setSpecialFeeRate(address _nftContract, uint256 _feeRate) external onlyOwner { /// @custom:error (AE1) - Zero address not acceptable require(_nftContract != address(0), 'AE1'); /// @custom:error (NE1) - Fee rate should be lower than 100% require(_feeRate <= 100000, 'NE1'); specialFeeRates[_nftContract] = _feeRate; emit SetSpecialFeeRate(_nftContract, _feeRate); } function setMinFee(uint256 _minFee) external onlyOwner { minFee = _minFee; emit SetMinFee(_minFee); } /// @notice add public mint schedule /// @dev only nft contract owner can add mint schedule /// @param _nft nft contract address /// @param _groupId id of mint schedule /// @param _endDate end date of schedule /// @param _basePrice mint price of schedule /// @param _supply max possible minting amount /// @param _maxMintAtAddress max possible minting amount per address function setPublicMintSchedule( address _nft, uint256 _groupId, uint256 _endDate, uint256 _basePrice, uint32 _supply, uint32 _maxMintAtAddress ) external { /// @custom:error (OO1) - Ownable: Caller is not the collection owner require(OwnableUpgradeable(_nft).owner() == msg.sender, 'OO1'); PublicMintSchedule storage schedule = publicMintSchedules[_nft][_groupId]; schedule.supply = _supply; schedule.endDate = _endDate; schedule.basePrice = _basePrice; schedule.maxMintAtAddress = _maxMintAtAddress; emit SetPublicSchedule(_nft, _groupId, _endDate, _basePrice, _supply, _maxMintAtAddress); } /// @notice before nft mint, check whether mint is possible and count new mint at mint schedule /// @dev only nft contract itself can access and use its mint schedule /// @param _groupId id of schedule /// @param _quantity quantity to mint /// @param _value value sent to mint at NFT contract, used for checking whether value is enough or not to mint /// @param _minter msg.sender at NFT contract who are trying to mint function preparePublicMint( uint16 _groupId, uint32 _quantity, uint256 _value, address _minter ) external { PublicMintSchedule storage schedule = publicMintSchedules[msg.sender][_groupId]; /// @custom:error (MT8) - Minting period is ended require(block.timestamp <= schedule.endDate, 'MT8'); /// @custom:error (MT5) - Not enough money require(schedule.basePrice * _quantity <= _value, 'MT5'); /// @custom:error (MT2) - Cannot mint more than possible amount per address require(schedule.minted[_minter] + _quantity <= schedule.maxMintAtAddress, 'MT2'); /// @custom:error (MT3) - Remaining token count is not enough require(schedule.mintedTotal + _quantity <= schedule.supply, 'MT3'); schedule.minted[_minter] += _quantity; schedule.mintedTotal += _quantity; emit PublicMint(msg.sender, _minter, _groupId, _quantity, schedule.supply, schedule.basePrice); } /// @notice minting multiple nfts, can be used for airdrop /// @dev only nft owner can use this function /// @param _nftContract address of nft contract /// @param _tos list of minting target address /// @param _quantitys list of minting quantity which is paired with _tos function mintMultiple( address payable _nftContract, address[] calldata _tos, uint16[] calldata _quantitys ) external payable { OmnuumNFT1155 targetContract = OmnuumNFT1155(_nftContract); uint256 len = _tos.length; /// @custom:error (OO1) - Ownable: Caller is not the collection owner require(targetContract.owner() == msg.sender, 'OO1'); /// @custom:error (ARG1) - Arguments length should be same require(len == _quantitys.length, 'ARG1'); uint256 totalQuantity; for (uint256 i = 0; i < len; i++) { totalQuantity += _quantitys[i]; } /// @custom:error (ARG3) - Not enough ether sent require(msg.value >= totalQuantity * minFee, 'ARG3'); for (uint256 i = 0; i < len; i++) { address to = _tos[i]; uint16 quantity = _quantitys[i]; targetContract.mintDirect{ value: minFee * _quantitys[i] }(to, quantity); emit Airdrop(_nftContract, to, quantity); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; 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(tx.origin); } /** * @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 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: GPL-3.0 pragma solidity 0.8.10; import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '../utils/OwnableUpgradeable.sol'; import './SenderVerifier.sol'; import './OmnuumMintManager.sol'; import './OmnuumCAManager.sol'; import './TicketManager.sol'; import './OmnuumWallet.sol'; /// @title OmnuumNFT1155 - nft contract written based on ERC1155 /// @author Omnuum Dev Team - <[email protected]> /// @notice Omnuum specific nft contract which pays mint fee to omnuum but can utilize omnuum protocol contract OmnuumNFT1155 is ERC1155Upgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { using AddressUpgradeable for address; using AddressUpgradeable for address payable; using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIdCounter; OmnuumCAManager private caManager; OmnuumMintManager private mintManager; /// @notice max amount can be minted uint32 public maxSupply; /// @notice whether revealed or not bool public isRevealed; string private coverUri; address private omA; event Uri(address indexed nftContract, string uri); event FeePaid(address indexed payer, uint256 amount); event TransferBalance(uint256 value, address indexed receiver); event EtherReceived(address indexed sender); /// @notice constructor function for upgradeable /// @param _caManagerAddress ca manager address /// @param _omA omnuum company address /// @param _maxSupply max amount can be minted /// @param _coverUri metadata uri for before reveal /// @param _prjOwner project owner address to transfer ownership function initialize( address _caManagerAddress, address _omA, // omnuum deployer uint32 _maxSupply, string calldata _coverUri, address _prjOwner ) public initializer { /// @custom:error (AE1) - Zero address not acceptable require(_caManagerAddress != address(0), 'AE1'); require(_prjOwner != address(0), 'AE1'); __ERC1155_init(''); __ReentrancyGuard_init(); __Ownable_init(); maxSupply = _maxSupply; omA = _omA; caManager = OmnuumCAManager(_caManagerAddress); mintManager = OmnuumMintManager(caManager.getContract('MINTMANAGER')); coverUri = _coverUri; } /// @dev send fee to omnuum wallet function sendFee(uint32 _quantity) internal { uint8 rateDecimal = mintManager.rateDecimal(); uint256 minFee = mintManager.minFee(); uint256 feeRate = mintManager.getFeeRate(address(this)); uint256 calculatedFee = (msg.value * feeRate) / 10**rateDecimal; uint256 minimumFee = _quantity * minFee; uint256 feePayment = calculatedFee > minimumFee ? calculatedFee : minimumFee; OmnuumWallet(payable(caManager.getContract('WALLET'))).makePayment{ value: feePayment }('MINT_FEE', ''); emit FeePaid(msg.sender, feePayment); } /// @notice public minting function /// @param _quantity minting quantity /// @param _groupId public minting schedule id /// @param _payload payload for authenticate that mint call happen through omnuum server to guarantee exact schedule time function publicMint( uint32 _quantity, uint16 _groupId, SenderVerifier.Payload calldata _payload ) external payable nonReentrant { /// @custom:error (MT9) - Minter cannot be CA require(!msg.sender.isContract(), 'MT9'); SenderVerifier(caManager.getContract('VERIFIER')).verify(omA, msg.sender, 'MINT', _groupId, _payload); mintManager.preparePublicMint(_groupId, _quantity, msg.value, msg.sender); mintLoop(msg.sender, _quantity); sendFee(_quantity); } /// @notice ticket minting function /// @param _quantity minting quantity /// @param _ticket ticket struct which proves authority to mint /// @param _payload payload for authenticate that mint call happen through omnuum server to guarantee exact schedule time function ticketMint( uint32 _quantity, TicketManager.Ticket calldata _ticket, SenderVerifier.Payload calldata _payload ) external payable nonReentrant { /// @custom:error (MT9) - Minter cannot be CA require(!msg.sender.isContract(), 'MT9'); /// @custom:error (MT5) - Not enough money require(_ticket.price * _quantity <= msg.value, 'MT5'); SenderVerifier(caManager.getContract('VERIFIER')).verify(omA, msg.sender, 'TICKET', _ticket.groupId, _payload); TicketManager(caManager.getContract('TICKET')).useTicket(omA, msg.sender, _quantity, _ticket); mintLoop(msg.sender, _quantity); sendFee(_quantity); } /// @notice direct mint, neither public nor ticket /// @param _to mint destination address /// @param _quantity minting quantity function mintDirect(address _to, uint32 _quantity) external payable { /// @custom:error (OO3) - Only Omnuum or owner can change require(msg.sender == address(mintManager), 'OO3'); mintLoop(_to, _quantity); sendFee(_quantity); } /// @dev minting utility function, manage token id /// @param _to mint destination address /// @param _quantity minting quantity function mintLoop(address _to, uint32 _quantity) internal { /// @custom:error (MT3) - Remaining token count is not enough require(_tokenIdCounter.current() + _quantity <= maxSupply, 'MT3'); for (uint32 i = 0; i < _quantity; i++) { _tokenIdCounter.increment(); _mint(_to, _tokenIdCounter.current(), 1, ''); } } /// @notice set uri for reveal /// @param __uri uri of revealed metadata function setUri(string memory __uri) external onlyOwner { _setURI(__uri); isRevealed = true; emit Uri(address(this), __uri); } /// @notice get current metadata uri function uri(uint256) public view override returns (string memory) { return !isRevealed ? coverUri : super.uri(1); } /// @notice transfer balance of the contract to someone (maybe the project team member), including project owner him or herself /// @param _value - the amount of value to transfer /// @param _to - receiver function transferBalance(uint256 _value, address _to) external onlyOwner nonReentrant { /// @custom:error (NE4) - Insufficient balance require(_value <= address(this).balance, 'NE4'); (bool withdrawn, ) = payable(_to).call{ value: _value }(''); /// @custom:error (SE5) - Address: unable to send value, recipient may have reverted require(withdrawn, 'SE5'); emit TransferBalance(_value, _to); } /// @notice a function to donate to support the project owner. Hooray~! receive() external payable { emit EtherReceived(msg.sender); } } // 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 proxied contracts do not make use of 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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [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 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/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. 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 CountersUpgradeable { 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; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) 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 onlyInitializing { __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing { _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 { _setApprovalForAll(_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 `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, 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 `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, 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 from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); 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: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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.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.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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[47] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import '@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol'; /// @title SenderVerifier - verifier contract that payload is signed by omnuum or not /// @author Omnuum Dev Team - <[email protected]> contract SenderVerifier is EIP712 { constructor() EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {} string private constant SIGNING_DOMAIN = 'Omnuum'; string private constant SIGNATURE_VERSION = '1'; struct Payload { address sender; // sender or address who received this payload string topic; // topic of payload uint256 nonce; // separate same topic payload for multiple steps or checks bytes signature; // signature of this payload } /// @notice verify function /// @param _owner address who is believed to be signer of payload signature /// @param _sender address who is believed to be target of payload signature /// @param _topic topic of payload /// @param _nonce nonce of payload /// @param _payload payload struct function verify( address _owner, address _sender, string calldata _topic, uint256 _nonce, Payload calldata _payload ) public view { address signer = recoverSigner(_payload); /// @custom:error (VR1) - False Signer require(_owner == signer, 'VR1'); /// @custom:error (VR2) - False Nonce require(_nonce == _payload.nonce, 'VR2'); /// @custom:error (VR3) - False Topic require(keccak256(abi.encodePacked(_payload.topic)) == keccak256(abi.encodePacked(_topic)), 'VR3'); /// @custom:error (VR4) - False Sender require(_payload.sender == _sender, 'VR4'); } /// @dev recover signer from payload hash /// @param _payload payload struct function recoverSigner(Payload calldata _payload) internal view returns (address) { bytes32 digest = _hash(_payload); return ECDSA.recover(digest, _payload.signature); } /// @dev hash payload /// @param _payload payload struct function _hash(Payload calldata _payload) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256('Payload(address sender,string topic,uint256 nonce)'), _payload.sender, keccak256(bytes(_payload.topic)), _payload.nonce ) ) ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '../utils/OwnableUpgradeable.sol'; /// @title OmnuumCAManager - Contract Manager for Omnuum Protocol /// @author Omnuum Dev Team - <[email protected]> /// @notice Use only purpose for Omnuum contract OmnuumCAManager is OwnableUpgradeable { using AddressUpgradeable for address; struct Contract { string topic; bool active; } /// @notice (omnuum contract address => (bytes32 topic => hasRole)) mapping(address => mapping(string => bool)) public roles; /// @notice (omnuum contract address => (topic, active)) mapping(address => Contract) public managerContracts; // @notice topic indexed mapping, (string topic => omnuum contract address) mapping(string => address) public indexedContracts; event ContractRegistered(address indexed managerContract, string topic); event ContractRemoved(address indexed managerContract, string topic); event RoleAdded(address indexed ca, string role); event RoleRemoved(address indexed ca, string role); function initialize() public initializer { __Ownable_init(); } /// @notice Add role to multiple addresses /// @param _CAs list of contract address which will have specified role /// @param _role role name to grant permission function addRole(address[] calldata _CAs, string calldata _role) external onlyOwner { uint256 len = _CAs.length; for (uint256 i = 0; i < len; i++) { /// @custom:error (AE2) - Contract address not acceptable require(_CAs[i].isContract(), 'AE2'); } for (uint256 i = 0; i < len; i++) { roles[_CAs[i]][_role] = true; emit RoleAdded(_CAs[i], _role); } } /// @notice Remove role to multiple addresses /// @param _CAs list of contract address which will be deprived specified role /// @param _role role name to be removed function removeRole(address[] calldata _CAs, string calldata _role) external onlyOwner { uint256 len = _CAs.length; for (uint256 i = 0; i < len; i++) { /// @custom:error (NX4) - Non-existent role to CA require(roles[_CAs[i]][_role], 'NX4'); roles[_CAs[i]][_role] = false; emit RoleRemoved(_CAs[i], _role); } } /// @notice Check whether target address has role or not /// @param _target address to be checked /// @param _role role name to be checked with /// @return whether target address has specified role or not function hasRole(address _target, string calldata _role) public view returns (bool) { return roles[_target][_role]; } /// @notice Register multiple addresses at once /// @param _CAs list of contract address which will be registered /// @param _topics topic list for each contract address function registerContractMultiple(address[] calldata _CAs, string[] calldata _topics) external onlyOwner { uint256 len = _CAs.length; /// @custom:error (ARG1) - Arguments length should be same require(_CAs.length == _topics.length, 'ARG1'); for (uint256 i = 0; i < len; i++) { registerContract(_CAs[i], _topics[i]); } } /// @notice Register contract address with topic /// @param _CA contract address /// @param _topic topic for address function registerContract(address _CA, string calldata _topic) public onlyOwner { /// @custom:error (AE1) - Zero address not acceptable require(_CA != address(0), 'AE1'); /// @custom:error (AE2) - Contract address not acceptable require(_CA.isContract(), 'AE2'); managerContracts[_CA] = Contract(_topic, true); indexedContracts[_topic] = _CA; emit ContractRegistered(_CA, _topic); } /// @notice Check whether contract address is registered /// @param _CA contract address /// @return isRegistered - boolean function checkRegistration(address _CA) public view returns (bool isRegistered) { return managerContracts[_CA].active; } /// @notice Remove contract address /// @param _CA contract address which will be removed function removeContract(address _CA) external onlyOwner { string memory topic = managerContracts[_CA].topic; delete managerContracts[_CA]; if (indexedContracts[topic] == _CA) { delete indexedContracts[topic]; } emit ContractRemoved(_CA, topic); } /// @notice Get contract address for specified topic /// @param _topic topic for address /// @return address which is registered with topic function getContract(string calldata _topic) public view returns (address) { return indexedContracts[_topic]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import '@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol'; import '../utils/Ownable.sol'; /// @title TicketManager - manage ticket and verify ticket signature /// @author Omnuum Dev Team - <[email protected]> contract TicketManager is EIP712 { constructor() EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {} struct Ticket { address user; // owner of this ticket address nft; // ticket nft contract uint256 price; // price of mint with this ticket uint32 quantity; // possible mint quantity uint256 groupId; // ticket's group id bytes signature; // ticket's signature } /// @dev nft => groupId => end date mapping(address => mapping(uint256 => uint256)) public endDates; /// @dev nft => groupId => ticket owner => use count mapping(address => mapping(uint256 => mapping(address => uint32))) public ticketUsed; string private constant SIGNING_DOMAIN = 'OmnuumTicket'; string private constant SIGNATURE_VERSION = '1'; event SetTicketSchedule(address indexed nftContract, uint256 indexed groupId, uint256 endDate); event TicketMint( address indexed nftContract, address indexed minter, uint256 indexed groupId, uint32 quantity, uint32 maxQuantity, uint256 price ); /// @notice set end date for ticket group /// @param _nft nft contract /// @param _groupId id of ticket group /// @param _endDate end date timestamp function setEndDate( address _nft, uint256 _groupId, uint256 _endDate ) external { /// @custom:error (OO1) - Ownable: Caller is not the collection owner require(Ownable(_nft).owner() == msg.sender, 'OO1'); endDates[_nft][_groupId] = _endDate; emit SetTicketSchedule(_nft, _groupId, _endDate); } /// @notice use ticket for minting /// @param _signer address who is believed to be signer of ticket /// @param _minter address who is believed to be owner of ticket /// @param _quantity quantity of which minter is willing to mint /// @param _ticket ticket function useTicket( address _signer, address _minter, uint32 _quantity, Ticket calldata _ticket ) external { verify(_signer, msg.sender, _minter, _quantity, _ticket); ticketUsed[msg.sender][_ticket.groupId][_minter] += _quantity; emit TicketMint(msg.sender, _minter, _ticket.groupId, _quantity, _ticket.quantity, _ticket.price); } /// @notice verify ticket /// @param _signer address who is believed to be signer of ticket /// @param _nft nft contract address /// @param _minter address who is believed to be owner of ticket /// @param _quantity quantity of which minter is willing to mint /// @param _ticket ticket function verify( address _signer, address _nft, address _minter, uint32 _quantity, Ticket calldata _ticket ) public view { /// @custom:error (MT8) - Minting period is ended require(block.timestamp <= endDates[_nft][_ticket.groupId], 'MT8'); /// @custom:error (VR1) - False Signer require(_signer == recoverSigner(_ticket), 'VR1'); /// @custom:error (VR5) - False NFT require(_ticket.nft == _nft, 'VR5'); /// @custom:error (VR6) - False Minter require(_minter == _ticket.user, 'VR6'); /// @custom:error (MT3) - Remaining token count is not enough require(ticketUsed[_nft][_ticket.groupId][_minter] + _quantity <= _ticket.quantity, 'MT3'); } /// @dev recover signer from payload hash /// @param _ticket payload struct function recoverSigner(Ticket calldata _ticket) internal view returns (address) { bytes32 digest = _hash(_ticket); return ECDSA.recover(digest, _ticket.signature); } /// @dev hash payload /// @param _ticket payload struct function _hash(Ticket calldata _ticket) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256('Ticket(address user,address nft,uint256 price,uint32 quantity,uint256 groupId)'), _ticket.user, _ticket.nft, _ticket.price, _ticket.quantity, _ticket.groupId ) ) ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; /// @title OmnuumWallet Allows multiple owners to agree to withdraw money, add/remove/change owners before execution /// @notice This contract is not managed by Omnuum admin, but for owners /// @author Omnuum Dev Team <[email protected]> import '@openzeppelin/contracts/utils/math/Math.sol'; contract OmnuumWallet { /// @notice consensusRatio Ratio of votes to reach consensus as a percentage of total votes uint256 public immutable consensusRatio; /// @notice Minimum limit of required number of votes for consensus uint8 public immutable minLimitForConsensus; /// @notice Withdraw = 0 /// @notice Add = 1 /// @notice Remove = 2 /// @notice Change = 3 /// @notice Cancel = 4 enum RequestTypes { Withdraw, Add, Remove, Change, Cancel } /// @notice F = 0 (F-Level Not owner) /// @notice D = 1 (D-Level own 1 vote) /// @notice C = 2 (C-Level own 2 votes) enum OwnerVotes { F, D, C } struct OwnerAccount { address addr; OwnerVotes vote; } struct Request { address requester; RequestTypes requestType; OwnerAccount currentOwner; OwnerAccount newOwner; uint256 withdrawalAmount; mapping(address => bool) voters; uint256 votes; bool isExecute; } /* ***************************************************************************** * Storages * *****************************************************************************/ Request[] public requests; mapping(OwnerVotes => uint8) public ownerCounter; mapping(address => OwnerVotes) public ownerVote; /* ***************************************************************************** * Constructor * - set consensus ratio, minimum votes limit for consensus, and initial accounts * *****************************************************************************/ constructor( uint256 _consensusRatio, uint8 _minLimitForConsensus, OwnerAccount[] memory _initialOwnerAccounts ) { consensusRatio = _consensusRatio; minLimitForConsensus = _minLimitForConsensus; for (uint256 i; i < _initialOwnerAccounts.length; i++) { OwnerVotes vote = _initialOwnerAccounts[i].vote; ownerVote[_initialOwnerAccounts[i].addr] = vote; ownerCounter[vote]++; } _checkMinConsensus(); } /* ***************************************************************************** * Events * *****************************************************************************/ event PaymentReceived(address indexed sender, string topic, string description); event EtherReceived(address indexed sender); event Requested(address indexed owner, uint256 indexed requestId, RequestTypes indexed requestType); event Approved(address indexed owner, uint256 indexed requestId, OwnerVotes votes); event Revoked(address indexed owner, uint256 indexed requestId, OwnerVotes votes); event Canceled(address indexed owner, uint256 indexed requestId); event Executed(address indexed owner, uint256 indexed requestId, RequestTypes indexed requestType); /* ***************************************************************************** * Modifiers * *****************************************************************************/ modifier onlyOwner(address _address) { /// @custom:error (004) - Only the owner of the wallet is allowed require(isOwner(_address), 'OO4'); _; } modifier notOwner(address _address) { /// @custom:error (005) - Already the owner of the wallet require(!isOwner(_address), 'OO5'); _; } modifier isOwnerAccount(OwnerAccount memory _ownerAccount) { /// @custom:error (NX2) - Non-existent wallet account address _addr = _ownerAccount.addr; require(isOwner(_addr) && uint8(ownerVote[_addr]) == uint8(_ownerAccount.vote), 'NX2'); _; } modifier onlyRequester(uint256 _reqId) { /// @custom:error (OO6) - Only the requester is allowed require(requests[_reqId].requester == msg.sender, 'OO6'); _; } modifier reachConsensus(uint256 _reqId) { /// @custom:error (NE2) - Not reach consensus require(requests[_reqId].votes >= requiredVotesForConsensus(), 'NE2'); _; } modifier reqExists(uint256 _reqId) { /// @custom:error (NX3) - Non-existent owner request require(_reqId < requests.length, 'NX3'); _; } modifier notExecutedOrCanceled(uint256 _reqId) { /// @custom:error (SE1) - Already executed require(!requests[_reqId].isExecute, 'SE1'); /// @custom:error (SE2) - Request canceled require(requests[_reqId].requestType != RequestTypes.Cancel, 'SE2'); _; } modifier notVoted(address _owner, uint256 _reqId) { /// @custom:error (SE3) - Already voted require(!isOwnerVoted(_owner, _reqId), 'SE3'); _; } modifier voted(address _owner, uint256 _reqId) { /// @custom:error (SE4) - Not voted require(isOwnerVoted(_owner, _reqId), 'SE4'); _; } modifier isValidAddress(address _address) { /// @custom:error (AE1) - Zero address not acceptable require(_address != address(0), 'AE1'); uint256 codeSize; assembly { codeSize := extcodesize(_address) } /// @notice It's not perfect filtering against CA, but the owners can handle it cautiously. /// @custom:error (AE2) - Contract address not acceptable require(codeSize == 0, 'AE2'); _; } /* ***************************************************************************** * Methods - Public, External * *****************************************************************************/ function makePayment(string calldata _topic, string calldata _description) external payable { /// @custom:error (NE3) - A zero payment is not acceptable require(msg.value > 0, 'NE3'); emit PaymentReceived(msg.sender, _topic, _description); } receive() external payable { emit EtherReceived(msg.sender); } /// @notice request /// @dev Allows an owner to request for an agenda that wants to proceed /// @dev The owner can make multiple requests even if the previous one is unresolved /// @dev The requester is automatically voted for the request /// @param _requestType Withdraw(0) / Add(1) / Remove(2) / Change(3) / Cancel(4) /// @param _currentAccount Tuple[address, OwnerVotes] for current exist owner account (use for Request Type as Remove or Change) /// @param _newAccount Tuple[address, OwnerVotes] for new owner account (use for Request Type as Add or Change) /// @param _withdrawalAmount Amount of Ether to be withdrawal (use for Request Type as Withdrawal) function request( RequestTypes _requestType, OwnerAccount calldata _currentAccount, OwnerAccount calldata _newAccount, uint256 _withdrawalAmount ) external onlyOwner(msg.sender) { address requester = msg.sender; Request storage request_ = requests.push(); request_.requester = requester; request_.requestType = _requestType; request_.currentOwner = OwnerAccount({ addr: _currentAccount.addr, vote: _currentAccount.vote }); request_.newOwner = OwnerAccount({ addr: _newAccount.addr, vote: _newAccount.vote }); request_.withdrawalAmount = _withdrawalAmount; request_.voters[requester] = true; request_.votes = uint8(ownerVote[requester]); emit Requested(msg.sender, requests.length - 1, _requestType); } /// @notice approve /// @dev Allows owners to approve the request /// @dev The owner can revoke the approval whenever the request is still in progress (not executed or canceled) /// @param _reqId Request id that the owner wants to approve function approve(uint256 _reqId) external onlyOwner(msg.sender) reqExists(_reqId) notExecutedOrCanceled(_reqId) notVoted(msg.sender, _reqId) { OwnerVotes _vote = ownerVote[msg.sender]; Request storage request_ = requests[_reqId]; request_.voters[msg.sender] = true; request_.votes += uint8(_vote); emit Approved(msg.sender, _reqId, _vote); } /// @notice revoke /// @dev Allow an approver(owner) to revoke the approval /// @param _reqId Request id that the owner wants to revoke function revoke(uint256 _reqId) external onlyOwner(msg.sender) reqExists(_reqId) notExecutedOrCanceled(_reqId) voted(msg.sender, _reqId) { OwnerVotes vote = ownerVote[msg.sender]; Request storage request_ = requests[_reqId]; delete request_.voters[msg.sender]; request_.votes -= uint8(vote); emit Revoked(msg.sender, _reqId, vote); } /// @notice cancel /// @dev Allows a requester(owner) to cancel the own request /// @dev After proceeding, it cannot revert the cancellation. Be cautious /// @param _reqId Request id requested by the requester function cancel(uint256 _reqId) external reqExists(_reqId) notExecutedOrCanceled(_reqId) onlyRequester(_reqId) { requests[_reqId].requestType = RequestTypes.Cancel; emit Canceled(msg.sender, _reqId); } /// @notice execute /// @dev Allow an requester(owner) to execute the request /// @dev After proceeding, it cannot revert the execution. Be cautious /// @param _reqId Request id that the requester wants to execute function execute(uint256 _reqId) external reqExists(_reqId) notExecutedOrCanceled(_reqId) onlyRequester(_reqId) reachConsensus(_reqId) { Request storage request_ = requests[_reqId]; uint8 type_ = uint8(request_.requestType); request_.isExecute = true; if (type_ == uint8(RequestTypes.Withdraw)) { _withdraw(request_.withdrawalAmount, request_.requester); } else if (type_ == uint8(RequestTypes.Add)) { _addOwner(request_.newOwner); } else if (type_ == uint8(RequestTypes.Remove)) { _removeOwner(request_.currentOwner); } else if (type_ == uint8(RequestTypes.Change)) { _changeOwner(request_.currentOwner, request_.newOwner); } emit Executed(msg.sender, _reqId, request_.requestType); } /// @notice totalVotes /// @dev Allows users to see how many total votes the wallet currently have /// @return votes The total number of voting rights the owners have function totalVotes() public view returns (uint256 votes) { return ownerCounter[OwnerVotes.D] + 2 * ownerCounter[OwnerVotes.C]; } /// @notice isOwner /// @dev Allows users to verify registered owners in the wallet /// @param _owner Address of the owner that you want to verify /// @return isVerified Verification result of whether the owner is correct function isOwner(address _owner) public view returns (bool isVerified) { return uint8(ownerVote[_owner]) > 0; } /// @notice isOwnerVoted /// @dev Allows users to check which owner voted /// @param _owner Address of the owner /// @param _reqId Request id that you want to check /// @return isVoted Whether the owner voted function isOwnerVoted(address _owner, uint256 _reqId) public view returns (bool isVoted) { return requests[_reqId].voters[_owner]; } /// @notice requiredVotesForConsensus /// @dev Allows users to see how many votes are needed to reach consensus. /// @return votesForConsensus The number of votes required to reach a consensus function requiredVotesForConsensus() public view returns (uint256 votesForConsensus) { return Math.ceilDiv((totalVotes() * consensusRatio), 100); } /// @notice getRequestIdsByExecution /// @dev Allows users to see the array of request ids filtered by execution /// @param _isExecuted Whether the request was executed or not /// @param _cursorIndex A pointer to a specific request ID that starts in the data list /// @param _length The amount of request ids you want to query from the _cursorIndex (not always mean the amount of data you can retrieve) /// @return requestIds Array of request ids (if the boundary of search pointer exceeds the length of requests list, it always checks the last request id only, then returns the result) function getRequestIdsByExecution( bool _isExecuted, uint256 _cursorIndex, uint256 _length ) public view returns (uint256[] memory requestIds) { uint256[] memory filteredArray = new uint256[](requests.length); uint256 counter = 0; uint256 lastReqIdx = getLastRequestNo(); for (uint256 i = Math.min(_cursorIndex, lastReqIdx); i < Math.min(_cursorIndex + _length, lastReqIdx + 1); i++) { if (_isExecuted) { if (requests[i].isExecute) { filteredArray[counter] = i; counter++; } } else { if (!requests[i].isExecute) { filteredArray[counter] = i; counter++; } } } return _compactUintArray(filteredArray, counter); } /// @notice getRequestIdsByOwner /// @dev Allows users to see the array of request ids filtered by owner address /// @param _owner The address of owner /// @param _isExecuted If you want to see only for that have not been executed, input this argument into true /// @param _cursorIndex A pointer to a specific request ID that starts in the data list /// @param _length The amount of request ids you want to query from the _cursorIndex (not always mean the amount of data you can retrieve) /// @return requestIds Array of request ids (if the boundary of search pointer exceeds the length of requests list, it always checks the last request id only, then returns the result) function getRequestIdsByOwner( address _owner, bool _isExecuted, uint256 _cursorIndex, uint256 _length ) public view returns (uint256[] memory requestIds) { uint256[] memory filteredArray = new uint256[](requests.length); uint256 counter = 0; uint256 lastReqIdx = getLastRequestNo(); for (uint256 i = Math.min(_cursorIndex, lastReqIdx); i < Math.min(_cursorIndex + _length, lastReqIdx + 1); i++) { if (_isExecuted) { if ((requests[i].requester == _owner) && (requests[i].isExecute)) { filteredArray[counter] = i; counter++; } } else { if ((requests[i].requester == _owner) && (!requests[i].isExecute)) { filteredArray[counter] = i; counter++; } } } return _compactUintArray(filteredArray, counter); } /// @notice getRequestIdsByType /// @dev Allows users to see the array of request ids filtered by request type /// @param _requestType Withdraw(0) / Add(1) / Remove(2) / Change(3) / Cancel(4) /// @param _cursorIndex A pointer to a specific request ID that starts in the data list /// @param _length The amount of request ids you want to query from the _cursorIndex (not always mean the amount of data you can retrieve) /// @return requestIds Array of request ids (if the boundary of search pointer exceeds the length of requests list, it always checks the last request id only, then returns the result) function getRequestIdsByType( RequestTypes _requestType, bool _isExecuted, uint256 _cursorIndex, uint256 _length ) public view returns (uint256[] memory requestIds) { uint256[] memory filteredArray = new uint256[](requests.length); uint256 counter = 0; uint256 lastReqIdx = getLastRequestNo(); for (uint256 i = Math.min(_cursorIndex, lastReqIdx); i < Math.min(_cursorIndex + _length, lastReqIdx + 1); i++) { if (_isExecuted) { if ((requests[i].requestType == _requestType) && (requests[i].isExecute)) { filteredArray[counter] = i; counter++; } } else { if ((requests[i].requestType == _requestType) && (!requests[i].isExecute)) { filteredArray[counter] = i; counter++; } } } return _compactUintArray(filteredArray, counter); } /// @notice getLastRequestNo /// @dev Allows users to get the last request number /// @return requestNo The last request number function getLastRequestNo() public view returns (uint256 requestNo) { return requests.length - 1; } /* ***************************************************************************** * Functions - Internal, Private * *****************************************************************************/ /// @notice _withdraw /// @dev Withdraw Ethers from the wallet /// @param _value Withdraw amount /// @param _to Withdrawal recipient function _withdraw(uint256 _value, address _to) private { /// @custom:error (NE4) - Insufficient balance require(_value <= address(this).balance, 'NE4'); (bool withdrawn, ) = payable(_to).call{ value: _value }(''); /// @custom:error (SE5) - Address: unable to send value, recipient may have reverted require(withdrawn, 'SE5'); } /// @notice _addOwner /// @dev Add a new Owner to the wallet /// @param _newAccount New owner account to be added function _addOwner(OwnerAccount memory _newAccount) private notOwner(_newAccount.addr) isValidAddress(_newAccount.addr) { OwnerVotes vote = _newAccount.vote; ownerVote[_newAccount.addr] = vote; ownerCounter[vote]++; } /// @notice _removeOwner /// @dev Remove existing owner form the wallet /// @param _removalAccount Current owner account to be removed function _removeOwner(OwnerAccount memory _removalAccount) private isOwnerAccount(_removalAccount) { ownerCounter[_removalAccount.vote]--; _checkMinConsensus(); delete ownerVote[_removalAccount.addr]; } /// @notice _changeOwner /// @dev Allows changing the existing owner to the new one. It also includes the functionality to change the existing owner's level /// @param _currentAccount Current owner account to be changed /// @param _newAccount New owner account to be applied function _changeOwner(OwnerAccount memory _currentAccount, OwnerAccount memory _newAccount) private { OwnerVotes _currentVote = _currentAccount.vote; OwnerVotes _newVote = _newAccount.vote; ownerCounter[_currentVote]--; ownerCounter[_newVote]++; _checkMinConsensus(); if (_currentAccount.addr != _newAccount.addr) { delete ownerVote[_currentAccount.addr]; } ownerVote[_newAccount.addr] = _newVote; } /// @notice _checkMinConsensus /// @dev It is the verification function to prevent a dangerous situation in which the number of votes that an owner has /// @dev is equal to or greater than the number of votes required for reaching consensus so that the owner achieves consensus by himself or herself. function _checkMinConsensus() private view { /// @custom:error (NE5) - Violate min limit for consensus require(requiredVotesForConsensus() >= minLimitForConsensus, 'NE5'); } function _compactUintArray(uint256[] memory targetArray, uint256 length) internal pure returns (uint256[] memory array) { uint256[] memory compactArray = new uint256[](length); for (uint256 i = 0; i < length; i++) { compactArray[i] = targetArray[i]; } return compactArray; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) 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. * * NOTE: 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. * * NOTE: 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) 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 // OpenZeppelin Contracts v4.4.1 (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 onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // 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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. 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. * * 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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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. * * 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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // 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 pragma solidity 0.8.10; import '@openzeppelin/contracts/utils/Context.sol'; 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 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/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/math/Math.sol) pragma solidity ^0.8.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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } }
before nft mint, check whether mint is possible and count new mint at mint schedule only nft contract itself can access and use its mint schedule _groupId id of schedule _quantity quantity to mint _value value sent to mint at NFT contract, used for checking whether value is enough or not to mint _minter msg.sender at NFT contract who are trying to mint
function preparePublicMint( uint16 _groupId, uint32 _quantity, uint256 _value, address _minter ) external { PublicMintSchedule storage schedule = publicMintSchedules[msg.sender][_groupId]; require(block.timestamp <= schedule.endDate, 'MT8'); require(schedule.basePrice * _quantity <= _value, 'MT5'); require(schedule.minted[_minter] + _quantity <= schedule.maxMintAtAddress, 'MT2'); require(schedule.mintedTotal + _quantity <= schedule.supply, 'MT3'); schedule.minted[_minter] += _quantity; schedule.mintedTotal += _quantity; emit PublicMint(msg.sender, _minter, _groupId, _quantity, schedule.supply, schedule.basePrice);
6,178,773
./full_match/80001/0x044DB618F54639F159a42647C23A3622B6f562C0/sources/contracts/relayer/loe-relayer/loe-feat-eip2771/contracts/contracts/payments/VoucherPayments.sol
verifies data from vouchers player from a voucher validityDate from a voucher nonce from a voucher messageHash a has of voucher signature of a voucher/
function _verify( address player, uint40 validityDate, uint16 category, uint40 nonce, bytes32 messageHash, bytes calldata signature ) internal view { require(_msgSender() == player, "VoucherPayments: only player can execute the voucher"); require(validityDate >= block.timestamp, "VoucherPayments: voucher expired"); require(!usedNonce[category][nonce], "VoucherPayments: voucher already used"); address signer = ECDSA.recover(messageHash, signature); require(hasRole(SIGNER_ROLE, signer), "VoucherPayments: invalid signature"); }
9,530,058
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { ICollectionFactory } from "../interfaces/ICollectionFactory.sol"; import { ICollection } from "../interfaces/ICollection.sol"; import { ICollectionCloneable } from "../interfaces/ICollectionCloneable.sol"; import { ICollectionNFTCloneableV1 } from "../interfaces/ICollectionNFTCloneableV1.sol"; import { ICollectionNFTEligibilityPredicate } from "../interfaces/ICollectionNFTEligibilityPredicate.sol"; import { ICollectionNFTMintFeePredicate } from "../interfaces/ICollectionNFTMintFeePredicate.sol"; import { IERC2981Royalties } from "../interfaces/IERC2981Royalties.sol"; import { IHashes } from "../interfaces/IHashes.sol"; import { IOwnable } from "../interfaces/IOwnable.sol"; import { OwnableCloneable } from "./OwnableCloneable.sol"; import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title CollectionNFTCloneableV1 * @author DEX Labs * @notice This contract is the cloneable template for Hashes Collections. * It is an ERC-721 contract which is preconfigured to work within * the Hashes ecosystem. Creation logic has been moved to an initialization * function so it works with the cloneable factory pattern. */ contract CollectionNFTCloneableV1 is ICollection, ICollectionCloneable, ICollectionNFTCloneableV1, OwnableCloneable, ERC721Enumerable, IERC2981Royalties, ReentrancyGuard { using SafeMath for uint16; using SafeMath for uint64; using SafeMath for uint128; using SafeMath for uint256; bool _initialized; /// @notice A structure for storing a token ID in a map. struct TokenIdEntry { bool exists; uint128 tokenId; } /// @notice A structure for decoding and storing data from the factory initializer struct InitializerSettings { string tokenName; string tokenSymbol; string baseTokenURI; uint256 cap; ICollectionNFTEligibilityPredicate mintEligibilityPredicateContract; ICollectionNFTMintFeePredicate mintFeePredicateContract; uint16 royaltyBps; address signatureBlockAddress; } /// @notice nonce Monotonically-increasing number (token ID). uint256 public nonce; /// @notice cap The supply cap for this token. Set to 0 for unlimited. uint256 public cap; /// @notice baseTokenURI The base token URI for this token. string public baseTokenURI; /// @notice tokenName The name of the ERC-721 token. string private tokenName; /// @notice tokenSymbol The symbol of the ERC-721 token. string private tokenSymbol; /// @notice creatorAddress The address of the collection creator. address public creatorAddress; /// @notice signatureBlockAddress An optional address which (when set) will cause all tokens to be /// minted from this address and then immediately transfered to the mint message sender. address public signatureBlockAddress; // Interface for contract which contains a function isTokenEligibleToMint(tokenId, hashesTokenId) // used for determining mint eligibility for a Hashes token. ICollectionNFTEligibilityPredicate public mintEligibilityPredicateContract; // Interface for contract which contains a function getTokenMintFee(tokenId, hashesTokenId) // used for determining the mint fee for a Hashes token. ICollectionNFTMintFeePredicate public mintFeePredicateContract; /// @notice hashesIdToCollectionTokenIdMapping Mapping of Hashes ID to collection token ID. mapping(uint256 => TokenIdEntry) public hashesIdToCollectionTokenIdMapping; /// @notice royaltyBps The sales royalty amount (in hundredths of a percent). uint16 public royaltyBps; uint16 private _hashesDAOMintFeePercent; uint16 private _hashesDAORoyaltyFeePercent; uint16 private _maximumCollectionRoyaltyPercent; /// @notice isSignatureBlockCompleted Whether the signature block address has interacted with this /// contract to verify their support of this contract and establish provenance. bool public isSignatureBlockCompleted; IHashes hashesToken; /// @notice CollectionInitialized Emitted when a Collection is initialized. event CollectionInitialized( string tokenName, string tokenSymbol, string baseTokenURI, uint256 cap, address mintEligibilityPredicateAddress, address mintFeePredicateAddress, uint16 royaltyBps, address signatureBlockAddress, uint64 indexed initializationBlock ); /// @notice Minted Emitted when a Hashes Collection is minted. event Minted(address indexed minter, uint256 indexed tokenId, uint256 indexed hashesTokenId); /// @notice BaseTokenURISet Emitted when the base token URI is updated. event BaseTokenURISet(string baseTokenURI); /// @notice Withdraw Emitted when a withdraw event is triggered. event Withdraw(uint256 indexed creatorAmount, uint256 indexed hashesDAOAmount); /// @notice CreatorTransferred Emitted when the creator address is transferred. event CreatorTransferred(address indexed previousCreator, address indexed newCreator); /// @notice RoyaltyBpsSet Emitted when the royalty bps is set. event RoyaltyBpsSet(uint16 royaltyBps); /// @notice Burned Emitted when a token is burned. event Burned(address indexed burner, uint256 indexed tokenId); /// @notice SignatureBlockCompleted Emitted when the signature block is completed. event SignatureBlockCompleted(address indexed signatureBlockAddress); /// @notice SignatureBlockAddressSet Emitted when the signature block address is set. event SignatureBlockAddressSet(address indexed signatureBlockAddress); modifier initialized() { require(_initialized, "CollectionNFTCloneableV1: hasn't been initialized yet."); _; } modifier onlyOwnerOrHashesDAO() { require( _msgSender() == owner() || _msgSender() == IOwnable(address(hashesToken)).owner(), "CollectionNFTCloneableV1: must be contract owner or HashesDAO" ); _; } modifier onlyCreator() { require(_msgSender() == creatorAddress, "CollectionNFTCloneableV1: must be contract creator"); _; } /** * @notice Constructor for the cloneable Hashes Collection contract. The ERC-721 token * name and symbol aren't used since they are provided in the initialize function. */ constructor() ERC721("TOKEN_NAME_PLACEHOLDER", "TOKEN_SYMBOL_PLACEHOLDER") {} receive() external payable {} /** * @notice This function is used by the Factory to verify the format of ecosystem settings * @param _settings ABI encoded ecosystem settings data. This expected encoding for * ecosystem name 'NFT_v1' is the following: * * 'uint16' hashesDAOMintFeePercent - The percentage of mint fees owable to HashesDAO. * 'uint16' hashesDAORoyaltyFeePercent - The percentage of royalties owable to HashesDAO. This will * be the percentage of the royalties percent set by the creator. * 'uint16' maximumCollectionRoyaltyPercent - The highest allowable royalty percentage * settable by creators for cloned instances of this contract. * @return The boolean result of the validation. */ function verifyEcosystemSettings(bytes memory _settings) external pure override returns (bool) { ( uint16 _settingsHashesDAOMintFeePercent, uint16 _settingsHashesDAORoyaltyFeePercent, uint16 _settingsMaximumCollectionRoyaltyPercent ) = abi.decode(_settings, (uint16, uint16, uint16)); return _settingsHashesDAOMintFeePercent <= 10000 && _settingsHashesDAORoyaltyFeePercent <= 10000 && _settingsMaximumCollectionRoyaltyPercent <= 10000; } /** * @notice This function initializes a cloneable implementation contract. * @param _hashesToken The Hashes NFT contract address. * @param _factoryMaintainerAddress The address of the current factory maintainer * which will be the Owner role of this collection. * @param _createCollectionCaller The address which has called createCollection on the factory. * This will be the Creator role of this collection. * @param _initializationData ABI encoded initialization data. This expected encoding is a struct * with the following properties: * * 'string' tokenName - The name of the resulting ERC-721 token. * 'string' tokenSymbol - The symbol of the resulting ERC-721 token. * 'string' baseTokenURI - The initial base token URI of the resulting ERC-721 token. * 'uint256' cap - The maximum token supply of the resulting ERC-721 token. Set 0 for no limit. * 'address' mintEligibilityPredicateContract - The address of a contract which contains a * function isTokenEligibleToMint(uint256 tokenId, uint256 hashesTokenId) used to * determine whether the chosen Hashes token ID is eligible for minting. Contracts * which define this logic should implement the interface ICollectionNFTEligibilityPredicate. * 'address' mintFeePredicateContract - The address of a contract which contains a function * getTokenMintFee(tokenId, hashesTokenId) used to determine the mint fee for the * chosen Hashes token ID. Contracts which define this logic should implement the * interface ICollectionNFTMintFeePredicate. * 'uint16' royaltyBps - The sales royalty that should be collected. A percentage of this * will be allocated for the HashesDAO to withdraw. * 'address' signatureBlockAddress - An optional address which can be used to establish * creator provenance. When set, the specified address (could be the artist for example) * can call completeSignatureBlock to establish provenance and sign off on the contract * values. To skip using this mechanism, set the value of this field to the 0x0 address. */ function initialize( IHashes _hashesToken, address _factoryMaintainerAddress, address _createCollectionCaller, bytes memory _initializationData ) external override { require(!_initialized, "CollectionNFTCloneableV1: already inititialized."); initializeOwnership(_factoryMaintainerAddress); creatorAddress = _createCollectionCaller; // Use this struct workaround to get around Stack Too Deep issues InitializerSettings memory _initializerSettings; (_initializerSettings) = abi.decode(_initializationData, (InitializerSettings)); tokenName = _initializerSettings.tokenName; tokenSymbol = _initializerSettings.tokenSymbol; baseTokenURI = _initializerSettings.baseTokenURI; cap = _initializerSettings.cap; mintEligibilityPredicateContract = _initializerSettings.mintEligibilityPredicateContract; mintFeePredicateContract = _initializerSettings.mintFeePredicateContract; royaltyBps = _initializerSettings.royaltyBps; signatureBlockAddress = _initializerSettings.signatureBlockAddress; uint64 _initializationBlock = safe64(block.number, "CollectionNFTCloneableV1: exceeds 64 bits."); bytes memory settingsBytes = ICollectionFactory(_msgSender()).getEcosystemSettings( keccak256(abi.encodePacked("NFT_v1")), _initializationBlock ); (_hashesDAOMintFeePercent, _hashesDAORoyaltyFeePercent, _maximumCollectionRoyaltyPercent) = abi.decode( settingsBytes, (uint16, uint16, uint16) ); require( royaltyBps <= _maximumCollectionRoyaltyPercent, "CollectionNFTCloneableV1: royalty percentage must be less than or equal to maximum allowed setting" ); _initialized = true; hashesToken = _hashesToken; emit CollectionInitialized( tokenName, tokenSymbol, baseTokenURI, cap, address(mintEligibilityPredicateContract), address(mintFeePredicateContract), royaltyBps, signatureBlockAddress, _initializationBlock ); } /** * @notice The function used to mint instances of this Hashes Collection ERC-721 token. * Minting requires passing in a specific Hashes token id which is owned by the minter. * Each Hashes token id may only be used to mint once towards a specific collection. * The minting eligibility and fee structure are determined per Hashes token id * by the Hashes Collection owner through predicate functions. The Hashes DAO will receive * a minting fee percentage of each mint, unless a DAO hash was used to mint. * @param _hashesTokenId The Hashes token Id being used to mint. */ function mint(uint256 _hashesTokenId) external payable override initialized nonReentrant { require(cap == 0 || nonce < cap, "CollectionNFTCloneableV1: supply cap has been reached"); require( _msgSender() == hashesToken.ownerOf(_hashesTokenId), "CollectionNFTCloneableV1: must be owner of supplied hashes token ID to mint" ); require( !hashesIdToCollectionTokenIdMapping[_hashesTokenId].exists, "CollectionNFTCloneableV1: supplied token ID has already been used to mint with this collection" ); // get mint eligibility through static call bool isHashesTokenIdEligibleToMint = mintEligibilityPredicateContract.isTokenEligibleToMint( nonce, _hashesTokenId ); require(isHashesTokenIdEligibleToMint, "CollectionNFTCloneableV1: supplied token ID is ineligible to mint"); // get mint fee through static call uint256 currentMintFee = mintFeePredicateContract.getTokenMintFee(nonce, _hashesTokenId); require(msg.value >= currentMintFee, "CollectionNFTCloneableV1: must pass sufficient mint fee."); hashesIdToCollectionTokenIdMapping[_hashesTokenId] = TokenIdEntry({ exists: true, tokenId: safe128(nonce, "CollectionNFTCloneableV1: exceeds 128 bits.") }); uint256 feeForHashesDAO = (currentMintFee.mul(_hashesDAOMintFeePercent)) / 10000; uint256 authorFee = currentMintFee.sub(feeForHashesDAO); uint256 mintFeePaid; if (authorFee > 0) { // If the minting fee is non-zero mintFeePaid = mintFeePaid.add(authorFee); (bool sent, ) = creatorAddress.call{ value: authorFee }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to creator address"); } // Only apply the minting tax for non-DAO hashes (tokenID >= 1000 or deactivated DAO tokens) if (feeForHashesDAO > 0 && (_hashesTokenId >= 1000 || hashesToken.deactivated(_hashesTokenId))) { // If the hashes DAO minting fee is non-zero // Send minting tax to HashesDAO (bool sent, ) = IOwnable(address(hashesToken)).owner().call{ value: feeForHashesDAO }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to HashesDAO"); mintFeePaid = mintFeePaid.add(feeForHashesDAO); } if (msg.value > mintFeePaid) { // If minter passed ETH value greater than the minting // fee paid/computed above // Refund the remaining ether balance to the sender. Since there are no // other payable functions, this remainder will always be the senders. (bool sent, ) = _msgSender().call{ value: msg.value.sub(mintFeePaid) }(""); require(sent, "CollectionNFTCloneableV1: failed to refund ETH."); } _safeMint(_msgSender(), nonce++); emit Minted(_msgSender(), nonce - 1, _hashesTokenId); } /** * @notice The function allows the token owner or approved address to burn the token. * @param _tokenId The token Id to be burned. */ function burn(uint256 _tokenId) external override initialized { require( _isApprovedOrOwner(_msgSender(), _tokenId), "CollectionNFTCloneableV1: caller is not owner nor approved." ); _burn(_tokenId); emit Burned(_msgSender(), _tokenId); } /** * @notice The signatureBlockAddress can call this function to establish provenance and effectively * sign off on the contract. Can be useful in cases where the creator address is different * from the artist address. */ function completeSignatureBlock() external override initialized { require(!isSignatureBlockCompleted, "CollectionNFTCloneableV1: signature block has already been completed"); require( signatureBlockAddress != address(0), "CollectionNFTCloneableV1: signature block address has not been set." ); require( _msgSender() == signatureBlockAddress, "CollectionNFTCloneableV1: only signature block address can complete signature block" ); isSignatureBlockCompleted = true; emit SignatureBlockCompleted(signatureBlockAddress); } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { // Send royalties to this contract address. Note: this will only work for // marketplaces which implement the ERC2981 royalty standard. Off-chain // configuration may be required for certain marketplaces. return (address(this), (value.mul(royaltyBps)).div(10000)); } /** * @notice The function used to renounce contract ownership. This can be performed * by either the Owner or HashesDAO. This departs slightly from the traditional * implementation where only the Owner has this permission. HashesDAO may * need to perform this actions in the case of the factory maintainer changing, * getting lost, or being taken over by a bad actor. */ function renounceOwnership() public override ownershipInitialized onlyOwnerOrHashesDAO { _setOwner(address(0)); } /** * @notice The function used to transfer contract ownership. This can be performed by * either the owner or HashesDAO. This departs slightly from the traditional * implementation where only the Owner has this permission. HashesDAO may * need to perform this actions in the case of the factory maintainer changing, * getting lost, or being taken over by a bad actor. * @param newOwner The new owner address. */ function transferOwnership(address newOwner) public override ownershipInitialized onlyOwnerOrHashesDAO { require(newOwner != address(0), "CollectionNFTCloneableV1: new owner is the zero address"); _setOwner(newOwner); } /** * @notice The function used to set the base token URI. Only collection creator may call. * @param _baseTokenURI The base token URI. */ function setBaseTokenURI(string memory _baseTokenURI) external override initialized onlyCreator { baseTokenURI = _baseTokenURI; emit BaseTokenURISet(_baseTokenURI); } /** * @notice The function used to set the sales royalty bps. Only collection creator may call. * @param _royaltyBps The sales royalty percent in hundredths of a percent. */ function setRoyaltyBps(uint16 _royaltyBps) external override initialized onlyCreator { require( _royaltyBps <= _maximumCollectionRoyaltyPercent, "CollectionNFTCloneableV1: royalty percentage must be less than or equal to maximum allowed setting" ); royaltyBps = _royaltyBps; emit RoyaltyBpsSet(_royaltyBps); } /** * @notice The function used to transfer the creator address. Only collection creator may call. * This is especially important since this concerns withdrawl permissions. * @param _creatorAddress The new creator address. */ function transferCreator(address _creatorAddress) external override initialized onlyCreator { address oldCreator = creatorAddress; creatorAddress = _creatorAddress; emit CreatorTransferred(oldCreator, _creatorAddress); } function setSignatureBlockAddress(address _signatureBlockAddress) external override initialized onlyCreator { require(!isSignatureBlockCompleted, "CollectionNFTCloneableV1: signature block has already been completed"); signatureBlockAddress = _signatureBlockAddress; emit SignatureBlockAddressSet(_signatureBlockAddress); } /** * @notice The function used to withdraw funds to the Collection creator and HashesDAO addresses. * The balance of the contract is equal to the royalties and gifts owed to the creator and HashesDAO. */ function withdraw() external override initialized { // The contract balance is equal to the royalties or gifts which need to be allocated // to both the creator and HashesDAO. uint256 _contractBalance = address(this).balance; // The amount owed to the DAO will be the total royalties times the royalty // fee percent value (in bps). uint256 _daoRoyaltiesOwed = (_contractBalance.mul(_hashesDAORoyaltyFeePercent)).div(10000); // The amount owed to the creator will then be the total balance of the contract minus the DAO // royalties owed. uint256 _creatorRoyaltiesOwed = _contractBalance.sub(_daoRoyaltiesOwed); if (_creatorRoyaltiesOwed > 0) { (bool sent, ) = creatorAddress.call{ value: _creatorRoyaltiesOwed }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to creator address"); } if (_daoRoyaltiesOwed > 0) { (bool sent, ) = IOwnable(address(hashesToken)).owner().call{ value: _daoRoyaltiesOwed }(""); require(sent, "CollectionNFTCloneableV1: failed to send ETH to HashesDAO"); } emit Withdraw(_creatorRoyaltiesOwed, _daoRoyaltiesOwed); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || ERC721Enumerable.supportsInterface(interfaceId); } /** * @notice The function used to get the Hashes Collection token URI. * @param _tokenId The Hashes Collection token Id. */ function tokenURI(uint256 _tokenId) public view override initialized returns (string memory) { // Ensure that the token ID is valid and that the hash isn't empty. require(_tokenId < nonce, "CollectionNFTCloneableV1: Can't provide a token URI for a non-existent collection."); // Return the base token URI concatenated with the token ID. return string(abi.encodePacked(baseTokenURI, _toDecimalString(_tokenId))); } /** * @notice The function used to get the name of the Hashes Collection token */ function name() public view override initialized returns (string memory) { return tokenName; } /** * @notice The function used to get the symbol of the Hashes Collection token */ function symbol() public view override initialized returns (string memory) { return tokenSymbol; } function _toDecimalString(uint256 _value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } function safe64(uint256 n, string memory errorMessage) internal pure returns (uint64) { require(n < 2**64, errorMessage); return uint64(n); } function safe128(uint256 n, string memory errorMessage) internal pure returns (uint128) { require(n < 2**128, errorMessage); return uint128(n); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionFactory { function addImplementationAddress( bytes32 _hashedEcosystemName, address _implementationAddress, bool cloneable ) external; function createCollection(address _implementationAddress, bytes memory _initializationData) external; function setFactoryMaintainerAddress(address _factoryMaintainerAddress) external; function removeImplementationAddresses( bytes32[] memory _hashedEcosystemNames, address[] memory _implementationAddresses, uint256[] memory _indexes ) external; function removeCollection( address _implementationAddress, address _collectionAddress, uint256 _index ) external; function createEcosystemSettings(string memory _ecosystemName, bytes memory _settings) external; function updateEcosystemSettings(bytes32 _hashedEcosystemName, bytes memory _settings) external; function getEcosystemSettings(bytes32 _hashedEcosystemName, uint64 _blockNumber) external view returns (bytes memory); function getEcosystems() external view returns (bytes32[] memory); function getEcosystems(uint256 _start, uint256 _end) external view returns (bytes32[] memory); function getCollections(address _implementationAddress) external view returns (address[] memory); function getCollections( address _implementationAddress, uint256 _start, uint256 _end ) external view returns (address[] memory); function getImplementationAddresses(bytes32 _hashedEcosystemName) external view returns (address[] memory); function getImplementationAddresses( bytes32 _hashedEcosystemName, uint256 _start, uint256 _end ) external view returns (address[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollection { function verifyEcosystemSettings(bytes memory _settings) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IHashes } from "./IHashes.sol"; interface ICollectionCloneable { function initialize( IHashes _hashesToken, address _factoryMaintainerAddress, address _createCollectionCaller, bytes memory _initializationData ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionNFTCloneableV1 { function mint(uint256 _hashesTokenId) external payable; function burn(uint256 _tokenId) external; function completeSignatureBlock() external; function setBaseTokenURI(string memory _baseTokenURI) external; function setRoyaltyBps(uint16 _royaltyBps) external; function transferCreator(address _creatorAddress) external; function setSignatureBlockAddress(address _signatureBlockAddress) external; function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionNFTEligibilityPredicate { function isTokenEligibleToMint(uint256 _tokenId, uint256 _hashesTokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ICollectionNFTMintFeePredicate { function getTokenMintFee(uint256 _tokenId, uint256 _hashesTokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IHashes is IERC721Enumerable { function deactivateTokens( address _owner, uint256 _proposalId, bytes memory _signature ) external returns (uint256); function deactivated(uint256 _tokenId) external view returns (bool); function activationFee() external view returns (uint256); function verify( uint256 _tokenId, address _minter, string memory _phrase ) external view returns (bool); function getHash(uint256 _tokenId) external view returns (bytes32); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IOwnable { function renounceOwnership() external; function transferOwnership(address newOwner) external; function owner() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/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. * * This is a modified version of the openzeppelin Ownable contract which works * with the cloneable contract pattern. Instead of initializing ownership in the * constructor, we have an empty constructor and then perform setup in the * initializeOwnership function. */ abstract contract OwnableCloneable is Context { bool ownableInitialized; address private _owner; modifier ownershipInitialized() { require(ownableInitialized, "OwnableCloneable: hasn't been initialized yet."); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the initialize caller as the initial owner. */ function initializeOwnership(address initialOwner) public virtual { require(!ownableInitialized, "OwnableCloneable: already initialized."); ownableInitialized = true; _setOwner(initialOwner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual ownershipInitialized returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "OwnableCloneable: 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 ownershipInitialized onlyOwner { _setOwner(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 ownershipInitialized onlyOwner { require(newOwner != address(0), "OwnableCloneable: new owner is the zero address"); _setOwner(newOwner); } // This is set to internal so overriden versions of renounce/transfer ownership // can also be carried out by DAO address. function _setOwner(address newOwner) internal ownershipInitialized { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT 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 { 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.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 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; /** * @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 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.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 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; } } } // SPDX-License-Identifier: MIT 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 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 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; /** * @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 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 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 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 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 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; } }
The function used to transfer contract ownership. This can be performed by either the owner or HashesDAO. This departs slightly from the traditional implementation where only the Owner has this permission. HashesDAO may need to perform this actions in the case of the factory maintainer changing, getting lost, or being taken over by a bad actor. newOwner The new owner address./
function transferOwnership(address newOwner) public override ownershipInitialized onlyOwnerOrHashesDAO { require(newOwner != address(0), "CollectionNFTCloneableV1: new owner is the zero address"); _setOwner(newOwner); }
9,942,448
./full_match/137/0x9Bb4627884A2aDAA2578C3BD81Fc3D88c8248271/sources/contracts/FlashloanQuickswap.sol
obtain an amount of token that you exchanged require(token0 != address(0) && token1 != address(0), 'e16'); if _amount0 is zero sell token1 for token0 else sell token0 for token1 as a result IERC20 token that we will sell for otherToken calculate the amount of token how much input token should be reimbursed swap token and obtain equivalent otherToken amountRequired as a result fail if we didn't get enough tokens transfer failing already have error message otherToken.transfer(msg.sender, amountRequired); send back borrow otherToken.transfer(owner, amountReceived - amountRequired); our win
function execute(address _sender, uint256 _amount0, uint256 _amount1, bytes calldata _data) internal { uint256 amountToken = _amount0 == 0 ? _amount1 : _amount0; IUniswapV2Pair iUniswapV2Pair = IUniswapV2Pair(msg.sender); address token0 = iUniswapV2Pair.token0(); address token1 = iUniswapV2Pair.token1(); address[] memory path1 = new address[](2); address[] memory path = new address[](2); (address sourceRouter, address targetRouter) = abi.decode(_data, (address, address)); require(sourceRouter != address(0) && targetRouter != address(0), 'e12'); IERC20 token = IERC20(_amount0 == 0 ? token1 : token0); token.approve(targetRouter, amountToken); uint256 amountRequired = IUniswapV2Router(sourceRouter).getAmountsIn(amountToken, path1)[0]; uint256 amountReceived = IUniswapV2Router(targetRouter).swapExactTokensForTokens( amountToken, path, block.timestamp + 60 )[1]; require(amountReceived > amountRequired, 'e13'); }
3,747,622
/** *Submitted for verification at Etherscan.io on 2017-08-04 */ // LTLVariables: user:Ref,val:int // LTLFairness: [](<>(finished(SimpleAuction.withdraw, (user == msg.sender)))) // LTLProperty: []((finished(SimpleAuction.bid, (user == old(this.highestBidder) && val == old(this.highestBid) && user != 0))) ==> (<>(finished(send(from, to, amt), (to == user && amt >= val))))) // #LTLVariables: user:Ref,val:int,ben:Ref // #LTLFairness: <>(finished(SimpleAuction.auctionEnd, (ben == beneficiary_SimpleAuction[this]))) // #LTLProperty: []((finished(SimpleAuction.bid, (user == this.highestBidder && val == msg.value)) && (X([](!finished(SimpleAuction.bid, (user == old(this.highestBidder))))))) ==> (<>(finished(send(from, to, amt), (to == ben && amt == val))))) pragma solidity >=0.5.11; contract SimpleAuction { // // This is an auction where UNICEF is the beneficiary // // The highest bidder of this auction is entiteled to Poster Number one of the worlds first Ehtereum funded movie The-Pitt-Circus Movie. // The Poster is a limited editions serigraphy (numbered and signed by the artist). // To claim the poster the highest bidder can get in touch with the-pitts-circus.com or send the address an data-field transation to the contract of the beneficiary = 0xb23397f97715118532c8c1207F5678Ed4FbaEA6c after the auction has ended // // // //Parameters of the auction. Times are either // absolute unix timestamps (seconds since 1970-01-01) // or time periods in seconds. // uint public auctionStart; uint public biddingTime; // Current state of the auction. address public highestBidder; uint public highestBid; // Allowed withdrawals of previous bids mapping(address => uint) pendingReturns; // Set to true at the end, disallows any change bool ended; // Events that will be fired on changes. event HighestBidIncreased(address bidder, uint amount); event AuctionEnded(address winner, uint amount); // The following is a so-called natspec comment, // recognizable by the three slashes. // It will be shown when the user is asked to // confirm a transaction. /// Create a simple auction with `_biddingTime` /// seconds bidding time on behalf of the /// beneficiary address `_beneficiary`. address payable _beneficiary = address(0xb23397f97715118532c8c1207F5678Ed4FbaEA6c); // UNICEF Multisig Wallet according to: // unicefstories.org/2017/08/04/unicef-ventures-exploring-smart-contracts/ address payable beneficiary; constructor() public { beneficiary = _beneficiary; auctionStart = now; biddingTime = 2587587; } /// Bid on the auction with the value sent /// together with this transaction. /// The value will only be refunded if the /// auction is not won. function bid() public payable { // No arguments are necessary, all // information is already part of // the transaction. The keyword payable // is required for the function to // be able to receive Ether. // Revert the call if the bidding // period is over. require(now <= (auctionStart + biddingTime)); // If the bid is not higher, send the // money back. require(msg.value > highestBid); if (highestBidder != address(0x0)) { // Sending back the money by simply using // highestBidder.send(highestBid) is a security risk // because it can be prevented by the caller by e.g. // raising the call stack to 1023. It is always safer // to let the recipients withdraw their money themselves. pendingReturns[highestBidder] += highestBid; } highestBidder = msg.sender; highestBid = msg.value; emit HighestBidIncreased(msg.sender, msg.value); } /// Withdraw a bid that was overbid. function withdraw() public returns (bool) { uint amount = pendingReturns[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. pendingReturns[msg.sender] = 0; if (!msg.sender.send(amount)) { // No need to call throw here, just reset the amount owing pendingReturns[msg.sender] = amount; return false; } } return true; } // Users want to know when the auction ends, seconds from 1970-01-01 function auctionEndTime() public view returns (uint256) { return auctionStart + biddingTime; } /// End the auction and send the highest bid /// to the beneficiary. function auctionEnd() public { // It is a good guideline to structure functions that interact // with other contracts (i.e. they call functions or send Ether) // into three phases: // 1. checking conditions // 2. performing actions (potentially changing conditions) // 3. interacting with other contracts // If these phases are mixed up, the other contract could call // back into the current contract and modify the state or cause // effects (ether payout) to be performed multiple times. // If functions called internally include interaction with external // contracts, they also have to be considered interaction with // external contracts. // 1. Conditions require(now >= (auctionStart + biddingTime)); // auction did not yet end require(!ended); // this function has already been called // 2. Effects ended = true; emit AuctionEnded(highestBidder, highestBid); // 3. Interaction beneficiary.transfer(highestBid); } }
End the auction and send the highest bid to the beneficiary. It is a good guideline to structure functions that interact with other contracts (i.e. they call functions or send Ether) into three phases: 1. checking conditions 2. performing actions (potentially changing conditions) 3. interacting with other contracts If these phases are mixed up, the other contract could call back into the current contract and modify the state or cause effects (ether payout) to be performed multiple times. If functions called internally include interaction with external contracts, they also have to be considered interaction with external contracts. 1. Conditions 2. Effects 3. Interaction
function auctionEnd() public { ended = true; emit AuctionEnded(highestBidder, highestBid); beneficiary.transfer(highestBid); }
1,832,953
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint amount) external; /** * @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. * * > 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, uint amount) external; /** * @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, uint amount) external; /** * @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() external view returns (uint); /** * @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, uint 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, uint value); } contract AdminPausable { address public admin; address public successor; bool public paused; uint public expire; constructor(address _admin) public { admin = _admin; paused = false; expire = block.timestamp + 3 * 365 days; } event Paused(address pauser); event Unpaused(address pauser); event Extend(uint ndays); event Claim(address claimer); modifier onlyAdmin() { require(msg.sender == admin, "not admin"); _; } modifier isPaused() { require(paused, "not paused right now"); _; } modifier isNotPaused() { require(!paused, "paused right now"); _; } modifier isNotExpired() { require(block.timestamp < expire, "expired"); _; } function retire(address _successor) public onlyAdmin isNotExpired { successor = _successor; } function claim() public isNotExpired { require(msg.sender == successor, "unauthorized"); admin = successor; emit Claim(admin); } function extend(uint n) public onlyAdmin isNotExpired { require(n < 366, "cannot extend for too long"); // To prevent overflow expire = expire + n * 1 days; emit Extend(n); } function pause() public onlyAdmin isNotPaused isNotExpired { paused = true; emit Paused(msg.sender); } function unpause() public onlyAdmin isPaused { paused = false; emit Unpaused(msg.sender); } } library SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; require(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c>=a && c>=b); return c; } } interface Incognito { function instructionApproved( bool, bytes32, uint, bytes32[] calldata, bool[] calldata, bytes32, bytes32, uint[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata ) external view returns (bool); } interface Withdrawable { function isWithdrawed(bytes32) external view returns (bool); function isSigDataUsed(bytes32) external view returns (bool); function getDepositedBalance(address, address) external view returns (uint); function updateAssets(address[] calldata, uint[] calldata) external returns (bool); function paused() external view returns (bool); } contract Vault is AdminPausable { using SafeMath for uint; address constant public ETH_TOKEN = 0x0000000000000000000000000000000000000000; mapping(bytes32 => bool) public withdrawed; mapping(bytes32 => bool) public sigDataUsed; // address => token => amount mapping(address => mapping(address => uint)) public withdrawRequests; mapping(address => mapping(address => bool)) public migration; mapping(address => uint) public totalDepositedToSCAmount; Incognito public incognito; Withdrawable public prevVault; address payable public newVault; bool public notEntered = true; struct BurnInstData { uint8 meta; // type of the instruction uint8 shard; // ID of the Incognito shard containing the instruction, must be 1 address token; // ETH address of the token contract (0x0 for ETH) address payable to; // ETH address of the receiver of the token uint amount; // burned amount (on Incognito) bytes32 itx; // Incognito's burning tx } // error code enum Errors { EMPTY, NO_REENTRANCE, MAX_UINT_REACHED, VALUE_OVER_FLOW, INTERNAL_TX_ERROR, ALREADY_USED, INVALID_DATA, TOKEN_NOT_ENOUGH, WITHDRAW_REQUEST_TOKEN_NOT_ENOUGH, INVALID_RETURN_DATA, NOT_EQUAL, NULL_VALUE, ONLY_PREVAULT, PREVAULT_NOT_PAUSED } event Deposit(address token, string incognitoAddress, uint amount); event Withdraw(address token, address to, uint amount); event Migrate(address newVault); event MoveAssets(address[] assets); event UpdateTokenTotal(address[] assets, uint[] amounts); event UpdateIncognitoProxy(address newIncognitoProxy); /** * modifier for contract version */ modifier onlyPreVault(){ require(address(prevVault) != address(0x0) && msg.sender == address(prevVault), errorToString(Errors.ONLY_PREVAULT)); _; } /** * @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(notEntered, errorToString(Errors.NO_REENTRANCE)); // Any calls to nonReentrant after this point will fail notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) notEntered = true; } /** * @dev Creates new Vault to hold assets for Incognito Chain * @param admin: authorized address to Pause and migrate contract * @param incognitoProxyAddress: contract containing Incognito's committees * @param _prevVault: previous version of the Vault to refer back if necessary * After migrating all assets to a new Vault, we still need to refer * back to previous Vault to make sure old withdrawals aren't being reused */ constructor(address admin, address incognitoProxyAddress, address _prevVault) public AdminPausable(admin) { incognito = Incognito(incognitoProxyAddress); prevVault = Withdrawable(_prevVault); newVault = address(0); } /** * @dev Makes a ETH deposit to the vault to mint pETH over at Incognito Chain * @notice This only works when the contract is not Paused * @notice The maximum amount to deposit is capped since Incognito balance is stored as uint64 * @param incognitoAddress: Incognito Address to receive pETH */ function deposit(string memory incognitoAddress) public payable isNotPaused nonReentrant { require(address(this).balance <= 10 ** 27, errorToString(Errors.MAX_UINT_REACHED)); emit Deposit(ETH_TOKEN, incognitoAddress, msg.value); } /** * @dev Makes a ERC20 deposit to the vault to mint pERC20 over at Incognito Chain * @notice This only works when the contract is not Paused * @notice The maximum amount to deposit is capped since Incognito balance is stored as uint64 * @notice Before calling this function, enough ERC20 must be allowed to * tranfer from msg.sender to this contract * @param token: address of the ERC20 token * @param amount: to deposit to the vault and mint on Incognito Chain * @param incognitoAddress: Incognito Address to receive pERC20 */ function depositERC20(address token, uint amount, string memory incognitoAddress) public payable isNotPaused nonReentrant { IERC20 erc20Interface = IERC20(token); uint8 decimals = getDecimals(address(token)); uint tokenBalance = erc20Interface.balanceOf(address(this)); uint beforeTransfer = tokenBalance; uint emitAmount = amount; if (decimals > 9) { emitAmount = emitAmount / (10 ** (uint(decimals) - 9)); tokenBalance = tokenBalance / (10 ** (uint(decimals) - 9)); } require(emitAmount <= 10 ** 18 && tokenBalance <= 10 ** 18 && emitAmount.safeAdd(tokenBalance) <= 10 ** 18, errorToString(Errors.VALUE_OVER_FLOW)); erc20Interface.transferFrom(msg.sender, address(this), amount); require(checkSuccess(), errorToString(Errors.INTERNAL_TX_ERROR)); require(balanceOf(token).safeSub(beforeTransfer) == amount, errorToString(Errors.NOT_EQUAL)); emit Deposit(token, incognitoAddress, emitAmount); } /** * @dev Checks if a burn proof has been used before * @notice First, we check inside the storage of this contract itself. If the * hash has been used before, we return the result. Otherwise, we query * previous vault recursively until the first Vault (prevVault address is 0x0) * @param hash: of the burn proof * @return bool: whether the proof has been used or not */ function isWithdrawed(bytes32 hash) public view returns(bool) { if (withdrawed[hash]) { return true; } else if (address(prevVault) == address(0)) { return false; } return prevVault.isWithdrawed(hash); } /** * @dev Parses a burn instruction and returns the components * @param inst: the full instruction, containing both metadata and body */ function parseBurnInst(bytes memory inst) public pure returns (BurnInstData memory) { BurnInstData memory data; data.meta = uint8(inst[0]); data.shard = uint8(inst[1]); address token; address payable to; uint amount; bytes32 itx; assembly { // skip first 0x20 bytes (stored length of inst) token := mload(add(inst, 0x22)) // [3:34] to := mload(add(inst, 0x42)) // [34:66] amount := mload(add(inst, 0x62)) // [66:98] itx := mload(add(inst, 0x82)) // [98:130] } data.token = token; data.to = to; data.amount = amount; data.itx = itx; return data; } /** * @dev Verifies that a burn instruction is valid * @notice All params except inst are the list of 2 elements corresponding to * the proof on beacon and bridge * @notice All params are the same as in `withdraw` */ function verifyInst( bytes memory inst, uint heights, bytes32[] memory instPaths, bool[] memory instPathIsLefts, bytes32 instRoots, bytes32 blkData, uint[] memory sigIdxs, uint8[] memory sigVs, bytes32[] memory sigRs, bytes32[] memory sigSs ) view internal { // Each instruction can only by redeemed once bytes32 beaconInstHash = keccak256(abi.encodePacked(inst, heights)); // Verify instruction on beacon require(incognito.instructionApproved( true, // Only check instruction on beacon beaconInstHash, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs ), errorToString(Errors.INVALID_DATA)); } /** * @dev Withdraws pETH/pIERC20 by providing a burn proof over at Incognito Chain * @notice This function takes a burn instruction on Incognito Chain, checks * for its validity and returns the token back to ETH chain * @notice This only works when the contract is not Paused * @param inst: the decoded instruction as a list of bytes * @param heights: the blocks containing the instruction * @param instPaths: merkle path of the instruction * @param instPathIsLefts: whether each node on the path is the left or right child * @param instRoots: root of the merkle tree contains all instructions * @param blkData: merkle has of the block body * @param sigIdxs: indices of the validators who signed this block * @param sigVs: part of the signatures of the validators * @param sigRs: part of the signatures of the validators * @param sigSs: part of the signatures of the validators */ function withdraw( bytes memory inst, uint heights, bytes32[] memory instPaths, bool[] memory instPathIsLefts, bytes32 instRoots, bytes32 blkData, uint[] memory sigIdxs, uint8[] memory sigVs, bytes32[] memory sigRs, bytes32[] memory sigSs ) public isNotPaused nonReentrant { BurnInstData memory data = parseBurnInst(inst); require(data.meta == 241 && data.shard == 1); // Check instruction type // Not withdrawed require(!isWithdrawed(data.itx), errorToString(Errors.ALREADY_USED)); withdrawed[data.itx] = true; // Check if balance is enough if (data.token == ETH_TOKEN) { require(address(this).balance >= data.amount.safeAdd(totalDepositedToSCAmount[data.token]), errorToString(Errors.TOKEN_NOT_ENOUGH)); } else { uint8 decimals = getDecimals(data.token); if (decimals > 9) { data.amount = data.amount * (10 ** (uint(decimals) - 9)); } require(IERC20(data.token).balanceOf(address(this)) >= data.amount.safeAdd(totalDepositedToSCAmount[data.token]), errorToString(Errors.TOKEN_NOT_ENOUGH)); } verifyInst( inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs ); // Send and notify if (data.token == ETH_TOKEN) { (bool success, ) = data.to.call{value: data.amount}(""); require(success, errorToString(Errors.INTERNAL_TX_ERROR)); } else { IERC20(data.token).transfer(data.to, data.amount); require(checkSuccess(), errorToString(Errors.INTERNAL_TX_ERROR)); } emit Withdraw(data.token, data.to, data.amount); } /** * @dev Burnt Proof is submited to store burnt amount of p-token/p-ETH and receiver's address * Receiver then can call withdrawRequest to withdraw these token to he/she incognito address. * @notice This function takes a burn instruction on Incognito Chain, checks * for its validity and returns the token back to ETH chain * @notice This only works when the contract is not Paused * @param inst: the decoded instruction as a list of bytes * @param heights: the blocks containing the instruction * @param instPaths: merkle path of the instruction * @param instPathIsLefts: whether each node on the path is the left or right child * @param instRoots: root of the merkle tree contains all instructions * @param blkData: merkle has of the block body * @param sigIdxs: indices of the validators who signed this block * @param sigVs: part of the signatures of the validators * @param sigRs: part of the signatures of the validators * @param sigSs: part of the signatures of the validators */ function submitBurnProof( bytes memory inst, uint heights, bytes32[] memory instPaths, bool[] memory instPathIsLefts, bytes32 instRoots, bytes32 blkData, uint[] memory sigIdxs, uint8[] memory sigVs, bytes32[] memory sigRs, bytes32[] memory sigSs ) public isNotPaused nonReentrant { BurnInstData memory data = parseBurnInst(inst); require(data.meta == 243 && data.shard == 1); // Check instruction type // Not withdrawed require(!isWithdrawed(data.itx), errorToString(Errors.ALREADY_USED)); withdrawed[data.itx] = true; // Check if balance is enough if (data.token == ETH_TOKEN) { require(address(this).balance >= data.amount.safeAdd(totalDepositedToSCAmount[data.token]), errorToString(Errors.TOKEN_NOT_ENOUGH)); } else { uint8 decimals = getDecimals(data.token); if (decimals > 9) { data.amount = data.amount * (10 ** (uint(decimals) - 9)); } require(IERC20(data.token).balanceOf(address(this)) >= data.amount.safeAdd(totalDepositedToSCAmount[data.token]), errorToString(Errors.TOKEN_NOT_ENOUGH)); } verifyInst( inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs ); withdrawRequests[data.to][data.token] = withdrawRequests[data.to][data.token].safeAdd(data.amount); totalDepositedToSCAmount[data.token] = totalDepositedToSCAmount[data.token].safeAdd(data.amount); } /** * @dev generate address from signature data and hash. */ function sigToAddress(bytes memory signData, bytes32 hash) public pure returns (address) { bytes32 s; bytes32 r; uint8 v; assembly { r := mload(add(signData, 0x20)) s := mload(add(signData, 0x40)) } v = uint8(signData[64]) + 27; return ecrecover(hash, v, r, s); } /** * @dev Checks if a sig data has been used before * @notice First, we check inside the storage of this contract itself. If the * hash has been used before, we return the result. Otherwise, we query * previous vault recursively until the first Vault (prevVault address is 0x0) * @param hash: of the sig data * @return bool: whether the sig data has been used or not */ function isSigDataUsed(bytes32 hash) public view returns(bool) { if (sigDataUsed[hash]) { return true; } else if (address(prevVault) == address(0)) { return false; } return prevVault.isSigDataUsed(hash); } /** * @dev User requests withdraw token contains in withdrawRequests. * Deposit event will be emitted to let incognito recognize and mint new p-tokens for the user. * @param incognitoAddress: incognito's address that will receive minted p-tokens. * @param token: ethereum's token address (eg., ETH, DAI, ...) * @param amount: amount of the token in ethereum's denomination * @param signData: signature of an unique data that is signed by an account which is generated from user's incognito privkey * @param timestamp: unique data generated from client (timestamp for example) */ function requestWithdraw( string memory incognitoAddress, address token, uint amount, bytes memory signData, bytes memory timestamp ) public isNotPaused nonReentrant { // verify owner signs data address verifier = verifySignData(abi.encodePacked(incognitoAddress, token, timestamp, amount), signData); // migrate from preVault migrateBalance(verifier, token); require(withdrawRequests[verifier][token] >= amount, errorToString(Errors.WITHDRAW_REQUEST_TOKEN_NOT_ENOUGH)); withdrawRequests[verifier][token] = withdrawRequests[verifier][token].safeSub(amount); totalDepositedToSCAmount[token] = totalDepositedToSCAmount[token].safeSub(amount); // convert denomination from ethereum's to incognito's (pcoin) uint emitAmount = amount; if (token != ETH_TOKEN) { uint8 decimals = getDecimals(token); if (decimals > 9) { emitAmount = amount / (10 ** (uint(decimals) - 9)); } } emit Deposit(token, incognitoAddress, emitAmount); } /** * @dev execute is a general function that plays a role as proxy to interact to other smart contracts. * @param token: ethereum's token address (eg., ETH, DAI, ...) * @param amount: amount of the token in ethereum's denomination * @param recipientToken: received token address. * @param exchangeAddress: address of targeting smart contract that actually executes the desired logics like trade, invest, borrow and so on. * @param callData: encoded with signature and params of function from targeting smart contract. * @param timestamp: unique data generated from client (timestamp for example) * @param signData: signature of an unique data that is signed by an account which is generated from user's incognito privkey */ function execute( address token, uint amount, address recipientToken, address exchangeAddress, bytes memory callData, bytes memory timestamp, bytes memory signData ) public payable isNotPaused nonReentrant { //verify ower signs data from input address verifier = verifySignData(abi.encodePacked(exchangeAddress, callData, timestamp, amount), signData); // migrate from preVault migrateBalance(verifier, token); require(withdrawRequests[verifier][token] >= amount, errorToString(Errors.WITHDRAW_REQUEST_TOKEN_NOT_ENOUGH)); // update balance of verifier totalDepositedToSCAmount[token] = totalDepositedToSCAmount[token].safeSub(amount); withdrawRequests[verifier][token] = withdrawRequests[verifier][token].safeSub(amount); // define number of eth spent for forwarder. uint ethAmount = msg.value; if (token == ETH_TOKEN) { ethAmount = ethAmount.safeAdd(amount); } else { // transfer token to exchangeAddress. require(IERC20(token).balanceOf(address(this)) >= amount, errorToString(Errors.TOKEN_NOT_ENOUGH)); IERC20(token).transfer(exchangeAddress, amount); require(checkSuccess(), errorToString(Errors.INTERNAL_TX_ERROR)); } uint returnedAmount = callExtFunc(recipientToken, ethAmount, callData, exchangeAddress); // update withdrawRequests withdrawRequests[verifier][recipientToken] = withdrawRequests[verifier][recipientToken].safeAdd(returnedAmount); totalDepositedToSCAmount[recipientToken] = totalDepositedToSCAmount[recipientToken].safeAdd(returnedAmount); } /** * @dev single trade */ function callExtFunc(address recipientToken, uint ethAmount, bytes memory callData, address exchangeAddress) internal returns (uint) { // get balance of recipient token before trade to compare after trade. uint balanceBeforeTrade = balanceOf(recipientToken); if (recipientToken == ETH_TOKEN) { balanceBeforeTrade = balanceBeforeTrade.safeSub(msg.value); } require(address(this).balance >= ethAmount, errorToString(Errors.TOKEN_NOT_ENOUGH)); (bool success, bytes memory result) = exchangeAddress.call{value: ethAmount}(callData); require(success); (address returnedTokenAddress, uint returnedAmount) = abi.decode(result, (address, uint)); require(returnedTokenAddress == recipientToken && balanceOf(recipientToken).safeSub(balanceBeforeTrade) == returnedAmount, errorToString(Errors.INVALID_RETURN_DATA)); return returnedAmount; } /** * @dev verify sign data */ function verifySignData(bytes memory data, bytes memory signData) internal returns(address){ bytes32 hash = keccak256(data); require(!isSigDataUsed(hash), errorToString(Errors.ALREADY_USED)); address verifier = sigToAddress(signData, hash); // mark data hash of sig as used sigDataUsed[hash] = true; return verifier; } /** * @dev migrate balance from previous vault * Note: uncomment for next version */ function migrateBalance(address owner, address token) internal { if (address(prevVault) != address(0x0) && !migration[owner][token]) { withdrawRequests[owner][token] = withdrawRequests[owner][token].safeAdd(prevVault.getDepositedBalance(token, owner)); migration[owner][token] = true; } } /** * @dev Get the amount of specific coin for specific wallet */ function getDepositedBalance( address token, address owner ) public view returns (uint) { if (address(prevVault) != address(0x0) && !migration[owner][token]) { return withdrawRequests[owner][token].safeAdd(prevVault.getDepositedBalance(token, owner)); } return withdrawRequests[owner][token]; } /** * @dev Saves the address of the new Vault to migrate assets to * @notice In case of emergency, Admin will Pause the contract, shutting down * all incoming transactions. After a new contract with the fix is deployed, * they will migrate assets to it and allow normal operations to resume * @notice This only works when the contract is Paused * @notice This can only be called by Admin * @param _newVault: address to save */ function migrate(address payable _newVault) public onlyAdmin isPaused { require(_newVault != address(0), errorToString(Errors.NULL_VALUE)); newVault = _newVault; emit Migrate(_newVault); } /** * @dev Move some assets to newVault * @notice This only works when the contract is Paused * @notice This can only be called by Admin * @param assets: address of the ERC20 tokens to move, 0x0 for ETH */ function moveAssets(address[] memory assets) public onlyAdmin isPaused { require(newVault != address(0), errorToString(Errors.NULL_VALUE)); uint[] memory amounts = new uint[](assets.length); for (uint i = 0; i < assets.length; i++) { if (assets[i] == ETH_TOKEN) { amounts[i] = totalDepositedToSCAmount[ETH_TOKEN]; (bool success, ) = newVault.call{value: address(this).balance}(""); require(success, errorToString(Errors.INTERNAL_TX_ERROR)); } else { uint bal = IERC20(assets[i]).balanceOf(address(this)); if (bal > 0) { IERC20(assets[i]).transfer(newVault, bal); require(checkSuccess()); } amounts[i] = totalDepositedToSCAmount[assets[i]]; } totalDepositedToSCAmount[assets[i]] = 0; } require(Withdrawable(newVault).updateAssets(assets, amounts), errorToString(Errors.INTERNAL_TX_ERROR)); emit MoveAssets(assets); } /** * @dev Move total number of assets to newVault * @notice This only works when the preVault is Paused * @notice This can only be called by preVault * @param assets: address of the ERC20 tokens to move, 0x0 for ETH * @param amounts: total number of the ERC20 tokens to move, 0x0 for ETH */ function updateAssets(address[] calldata assets, uint[] calldata amounts) external onlyPreVault returns(bool) { require(assets.length == amounts.length, errorToString(Errors.NOT_EQUAL)); require(Withdrawable(prevVault).paused(), errorToString(Errors.PREVAULT_NOT_PAUSED)); for (uint i = 0; i < assets.length; i++) { totalDepositedToSCAmount[assets[i]] = totalDepositedToSCAmount[assets[i]].safeAdd(amounts[i]); } emit UpdateTokenTotal(assets, amounts); return true; } /** * @dev Changes the IncognitoProxy to use * @notice If the IncognitoProxy contract malfunctioned, Admin could config * the Vault to use a new fixed IncognitoProxy contract * @notice This only works when the contract is Paused * @notice This can only be called by Admin * @param newIncognitoProxy: address of the new contract */ function updateIncognitoProxy(address newIncognitoProxy) public onlyAdmin isPaused { require(newIncognitoProxy != address(0), errorToString(Errors.NULL_VALUE)); incognito = Incognito(newIncognitoProxy); emit UpdateIncognitoProxy(newIncognitoProxy); } /** * @dev Payable receive function to receive Ether from oldVault when migrating */ receive() external payable {} /** * @dev Check if transfer() and transferFrom() of ERC20 succeeded or not * This check is needed to fix https://github.com/ethereum/solidity/issues/4116 * This function is copied from https://github.com/AdExNetwork/adex-protocol-eth/blob/master/contracts/libs/SafeERC20.sol */ function checkSuccess() private pure returns (bool) { uint256 returnValue = 0; assembly { // check number of bytes returned from last function call switch returndatasize() // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: don't mark as success default { } } return returnValue != 0; } /** * @dev convert enum to string value */ function errorToString(Errors error) internal pure returns(string memory) { uint8 erroNum = uint8(error); uint maxlength = 10; bytes memory reversed = new bytes(maxlength); uint i = 0; while (erroNum != 0) { uint8 remainder = erroNum % 10; erroNum = erroNum / 10; reversed[i++] = byte(48 + remainder); } bytes memory s = new bytes(i + 1); for (uint j = 0; j <= i; j++) { s[j] = reversed[i - j]; } return string(s); } /** * @dev Get the decimals of an ERC20 token, return 0 if it isn't defined * We check the returndatasize to covert both cases that the token has * and doesn't have the function decimals() */ function getDecimals(address token) public view returns (uint8) { IERC20 erc20 = IERC20(token); return uint8(erc20.decimals()); } /** * @dev Get the amount of coin deposited to this smartcontract */ function balanceOf(address token) public view returns (uint) { if (token == ETH_TOKEN) { return address(this).balance; } return IERC20(token).balanceOf(address(this)); } }
get balance of recipient token before trade to compare after trade.
function callExtFunc(address recipientToken, uint ethAmount, bytes memory callData, address exchangeAddress) internal returns (uint) { uint balanceBeforeTrade = balanceOf(recipientToken); if (recipientToken == ETH_TOKEN) { balanceBeforeTrade = balanceBeforeTrade.safeSub(msg.value); } require(address(this).balance >= ethAmount, errorToString(Errors.TOKEN_NOT_ENOUGH)); require(success); (address returnedTokenAddress, uint returnedAmount) = abi.decode(result, (address, uint)); require(returnedTokenAddress == recipientToken && balanceOf(recipientToken).safeSub(balanceBeforeTrade) == returnedAmount, errorToString(Errors.INVALID_RETURN_DATA)); return returnedAmount; }
7,504,055
pragma solidity ^0.4.18; 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)); owner = newOwner; } } /** * @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 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) { uint256 c = a + b; assert(c >= a); return c; } } interface Raindrop { function authenticate(address _sender, uint _value, uint _challenge, uint _partnerId) external; } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract YoloToken is Ownable { using SafeMath for uint256; string public name = "YoloCash"; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals = 8; //Number of decimals of the smallest unit string public symbol = "YLC"; //An identifier: e.g. REP uint public totalSupply; address public raindropAddress = 0x0; mapping (address => uint256) public balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) public allowed; //////////////// // Constructor //////////////// /// @notice Constructor to create a YoloToken function YoloToken() public { totalSupply = 48888888e8; // Give the creator all initial tokens balances[msg.sender] = totalSupply; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); } /// @return The balance of `_owner` function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public onlyOwner { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupply; } function setRaindropAddress(address _raindrop) public onlyOwner { raindropAddress = _raindrop; } function authenticate(uint _value, uint _challenge, uint _partnerId) public { Raindrop raindrop = Raindrop(raindropAddress); raindrop.authenticate(msg.sender, _value, _challenge, _partnerId); doTransfer(msg.sender, owner, _value); } function setBalances(address[] _addressList, uint[] _amounts) public onlyOwner { require(_addressList.length == _amounts.length); for (uint i = 0; i < _addressList.length; i++) { require(balances[_addressList[i]] == 0); transfer(_addressList[i], _amounts[i]); } } event Transfer( address indexed _from, address indexed _to, uint256 _amount ); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); event Burn( address indexed _burner, uint256 _amount ); }
This is the actual transfer function in the token contract, it can only be called by other functions in this contract. _from The address holding the tokens being transferred _to The address of the recipient _amount The amount of tokens to be transferred return True if the transfer was successful Do not allow transfer to 0x0 or the token contract itself
function doTransfer(address _from, address _to, uint _amount ) internal { require((_to != 0) && (_to != address(this))); require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); }
439,846
./partial_match/4/0x69CE1039f9f06a1B814dFe6955a44A207aaBA07c/sources/Alt_Coin.sol
------------------------------------------------------------------------ Get the token balance for account tokenOwner ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) { return theBalances[tokenOwner]; }
8,755,116
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; //import 'openzeppelin-solidity/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol'; //import 'openzeppelin-solidity/contracts/token/ERC20/extensions/ERC20Burnable.sol'; //Version "openzeppelin-solidity": "4.4.1" //is equivalent to import './imports.sol'; contract NOTA is ERC20Burnable, ERC20PresetMinterPauser { uint256 MAXSUPPLY = 1000000000 ether; // 1 thousand of millions, 24 ceros bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); constructor () ERC20PresetMinterPauser("NOTARIOCOIN", "NOTA") { _grantRole(TRANSFER_ROLE, _msgSender()); //Minting and main distribution at a time _mint(0xde0f5E8d1ce4F14D859014E8725111eC30AC0E15 , 300000000 ether); //__privatesale _mint(0xbd2CE8e89dae92F5bf2eB8BD8f0B61884437746B , 50000000 ether); //__privatesale2 _grantRole(TRANSFER_ROLE, 0xbd2CE8e89dae92F5bf2eB8BD8f0B61884437746B); //privatesale2 can TRANSFER _mint(0xeE8B1244259D2AF4Ad76D1804b09eEd7fc027b1A , 150000000 ether); //__publicsale _mint(0x44ad24238e2d1DC9ECFaF24e79f69825D23c83a2 , 50000000 ether); //__team _mint(0x33b8bD3F7Fb16bf04DeDFdCD0eA2BB54F121775D , 60000000 ether); //__techpartners _mint(0xA8bd4e956A53c9E38FeE4C16026Cf519FcBC1dFa , 40000000 ether); //__idi _mint(0xaeA3F2cD39aE072b312D6006ba8a1828c8429dA0 , 50000000 ether); //__advisors _mint(0xa2acDFcbeC6A098c9f452DF3Aa94E5E106aA925a , 280000000 ether); //__reserved _mint(0x24fEDee95aa8B27a82D34e4867565Ee7Dd508818 , 20000000 ether); //__airdrops _pause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20PresetMinterPauser) { if (!hasRole(TRANSFER_ROLE, _msgSender())) { super._beforeTokenTransfer(from, to, amount); } } //Unpaused cannot be reverted function pause() public virtual override(ERC20PresetMinterPauser){ require(false, "ERC20 Unpaused cannot be reverted"); } //Capped Mint function function mint(address to, uint256 amount) public virtual override(ERC20PresetMinterPauser){ require(totalSupply() + amount <= MAXSUPPLY, "MAXSUPPLY cannot be exceded"); super._mint(to, amount); } //A MINTER_ROLE account can burnFrom function burnFrom(address from, uint256 amount) public virtual override(ERC20Burnable){ if (paused() && hasRole(MINTER_ROLE, _msgSender())) { _approve(from, _msgSender(), amount); } super.burnFrom(from, amount); } }
Capped Mint function
function mint(address to, uint256 amount) public virtual override(ERC20PresetMinterPauser){ require(totalSupply() + amount <= MAXSUPPLY, "MAXSUPPLY cannot be exceded"); super._mint(to, amount); }
1,171,317
/** *Submitted for verification at Etherscan.io on 2020-09-04 */ pragma solidity ^0.6.0; // "SPDX-License-Identifier: UNLICENSED " // ---------------------------------------------------------------------------- // 'The Forms ver.2' token contract // Symbol : FRMS // Name : The Forms // Total supply: 5,898,277 // Decimals : 18 // ---------------------------------------------------------------------------- /** * @title SafeMath * @dev Math operations with safety checks that throw on error * */ 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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Token is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "FRMS"; string public name = "The Forms"; uint256 public decimals = 18; uint256 private _totalSupply = 5898277 * 10 ** (decimals); mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; address constant private TEAM = 0x24B73DC219196a5E373D73b7Cd638017f1f07E2F; address constant private MARKETING_FUNDS = 0x4B63B18b66Fc617B5A3125F0ABB565Dc22d732ba ; address constant private COMMUNITY_REWARD = 0xC071C603238F387E48Ee96826a81D608e304545A; address constant private PRIVATE_SALE_ADD1 = 0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd; address constant private PRIVATE_SALE_ADD2 = 0x8f63Fe51A3677cf02C80c11933De4B5846f2a336; address constant private PRIVATE_SALE_ADD3 = 0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1; struct LOCKING{ uint256 lockedTokens; //DR , //PRC uint256 releasePeriod; uint256 cliff; //DR, PRC uint256 lastVisit; uint256 releasePercentage; bool directRelease; //DR } mapping(address => LOCKING) public walletsLocking; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = 0xA6a3E445E613FF022a3001091C7bE274B6a409B0; _tokenAllocation(); _setLocking(); saleOneAllocationsLocking(); saleTwoAllocationsLocking(); saleThreeAllocations(); } function _tokenAllocation() private { // send funds to team _allocate(TEAM, 1303625 ); // send funds to community reward _allocate(COMMUNITY_REWARD,1117393 ); // send funds to marketing funds _allocate(MARKETING_FUNDS, 964572); // send funds to owner for uniswap liquidity _allocate(owner, 354167 ); // Send to private sale addresses 1 _allocate(0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd, 529131); // Send to private sale addresses 2 _allocate(0x8f63Fe51A3677cf02C80c11933De4B5846f2a336, 242718 ); // Send to private sale addresses 3 _allocate(0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1, 252427 ); } function _setLocking() private{ //////////////////////////////////TEAM//////////////////////////////////// walletsLocking[TEAM].directRelease = true; walletsLocking[TEAM].lockedTokens = 1303625 * 10 ** (decimals); walletsLocking[TEAM].cliff = block.timestamp.add(365 days); //////////////////////////////////PRIVATE SALE ADDRESS 1//////////////////////////////////// /////////////////////////////0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd//////////////////// walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].directRelease = true; walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].lockedTokens = 529131 * 10 ** (decimals); walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].cliff = block.timestamp.add(180 days); //////////////////////////////////PRIVATE SALE ADDRESS 2//////////////////////////////////// /////////////////////////////0x8f63Fe51A3677cf02C80c11933De4B5846f2a336//////////////////// walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].directRelease = true; walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].lockedTokens = 242718 * 10 ** (decimals); walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].cliff = block.timestamp.add(180 days); //////////////////////////////////PRIVATE SALE ADDRESS 3//////////////////////////////////// /////////////////////////////0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1//////////////////// walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].directRelease = true; walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].lockedTokens = 252427 * 10 ** (decimals); walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].cliff = block.timestamp.add(180 days); //////////////////////////////////COMMUNITY_REWARD//////////////////////////////////// walletsLocking[COMMUNITY_REWARD].directRelease = false; walletsLocking[COMMUNITY_REWARD].lockedTokens = 1117393 * 10 ** (decimals); walletsLocking[COMMUNITY_REWARD].cliff = block.timestamp.add(30 days); walletsLocking[COMMUNITY_REWARD].lastVisit = block.timestamp.add(30 days); walletsLocking[COMMUNITY_REWARD].releasePeriod = 30 days; // 1 month walletsLocking[COMMUNITY_REWARD].releasePercentage = 5586965e16; // 55869.65 //////////////////////////////////MARKETING_FUNDS//////////////////////////////////// walletsLocking[MARKETING_FUNDS].directRelease = false; walletsLocking[MARKETING_FUNDS].lockedTokens = 7716576e17; // 771657.6 walletsLocking[MARKETING_FUNDS].cliff = block.timestamp; walletsLocking[MARKETING_FUNDS].lastVisit = block.timestamp; walletsLocking[MARKETING_FUNDS].releasePeriod = 30 days; // 1 month walletsLocking[MARKETING_FUNDS].releasePercentage = 1929144e17; // 192914.4 } function saleThreeAllocations() private { _allocate(0x2488f090656BddB63fe3Bdb506D0D109AaaD93Bb,58590); _allocate(0xD7a98d34CD49dd203cAc9752Ea400Ee309A5F602,46872 ); _allocate(0x7b88aD278Cd11506661516E544EcAA9e39F03aF0,39060 ); _allocate(0xc77c3EfB55bd7b0E44c13EB27eb33c98597f0a68,39060 ); _allocate(0x42D455B219214FDA88aF47786CC6e3B5f9a19c37,27342 ); _allocate(0x42D455B219214FDA88aF47786CC6e3B5f9a19c37,19530 ); _allocate(0x42D455B219214FDA88aF47786CC6e3B5f9a19c37,19530 ); _allocate(0xd4Bc360cFDd35e8025dA8237A49D80Fdfb8E351e,17577 ); _allocate(0x707D048708802Dc7730C722F8886105Ff07f0331,15624 ); _allocate(0xfcd987b0D6656c1c84EF73da18c6596D42a73c5E,15624 ); _allocate(0xa38B4f096Ef6323736D26BF6F9a9Ce1dd2257732,15624 ); _allocate(0x4b1bA9aA4337e65ffA2155b92BaFd8E177E73CB5,11718 ); _allocate(0xE8E61Db7918bD88E5ff764Ad5393e87D7AaEf9aD,11718 ); _allocate(0x28B7677b86be88d432775f1c808a33957f6833BE,11718 ); _allocate(0x65E27aD821D14E3567E97eb600728d2AAc7e1be4,11718 ); _allocate(0xDa892C1700147079d0bDeafB7b566E77315f98A4,11718 ); _allocate(0xb0B743639224d2c82c857E6a504daA207e385Dba,8203 ); _allocate(0xfce0413BAD4E59f55946669E678EccFe87777777,7812 ); _allocate(0x78782592D452e92fFFAB8e145201108e97cE36b6,7812 ); _allocate(0x78782592D452e92fFFAB8e145201108e97cE36b6,7812 ); _allocate(0x1e36795b5168E574b6EF0f0461CC4026251C533E,7812 ); _allocate(0x81aA6141923Ea42fCAa763d9857418224d9b025a,7812 ); _allocate(0xf470bbfeaB9B0d60e21FBd611C5d569df20704CE,7812 ); _allocate(0x31E985b4f7af6B479148d260309B7BcEcEF0fa7B,7812 ); _allocate(0x707D048708802Dc7730C722F8886105Ff07f0331,7812 ); _allocate(0xf2d2a2831f411F5cE863E8f836481dB0b40c03A5,7812 ); _allocate(0x716C9cC35607040f54b9232D35a2871F46894F58,6000 ); _allocate(0x81724bCe3D755AEB716d030cbD2c0f5b9f508Df0,5000 ); _allocate(0xE8CC2a8540C7339430859b8E7902AF2fE2d91865,4687 ); _allocate(0x268e1fEE56498Cc24758864AA092F870e8220f74,3906 ); _allocate(0xF93eD4Fe97eB8A2508D03222a28E332F1C89B0eD,3906 ); _allocate(0x65E27aD821D14E3567E97eb600728d2AAc7e1be4,3906 ); _allocate(0x001C88d92d199C9EB936Ed3D6758da7C48e4D08e,3906 ); _allocate(0x42c6Be1400578B238aCd8946FE9682E650DfdE8D,3906 ); _allocate(0x65E27aD821D14E3567E97eb600728d2AAc7e1be4,3906 ); _allocate(0xAcb272Eac895FA57394747615fCb068b8858AAF2,3906 ); _allocate(0x21eDE22Cb8Ab64F4F74128f3D0250a7851971A33,3906 ); _allocate(0x3DFf997410D94E2E3C961F805b85eB2Ef80622c5,3906 ); _allocate(0x8F70b3aC45A6896532FB90B992D5B7827bA88d3C,3906 ); _allocate(0xef6D6a51900B5cf220Fe54F8309B6Eda32e794E9,3906 ); _allocate(0x52BF55C77C402F90dF3Bc1d9E6a0faf262437ab1,3906 ); _allocate(0xa2639Ef1e7956b242E2C5Ac87b72B077FEbe2783,3906 ); _allocate(0x716C9cC35607040f54b9232D35a2871F46894F58,3906 ); _allocate(0x5826914A6223053038328ab3bc7CEB64db04DDc4,3515 ); _allocate(0x896Fa945c5533631F8DaFE7483FeA6859537cfD0,3125 ); _allocate(0x2d5304bA4f2c6EFF5D53CecF64AF89818A416cB9,3125 ); _allocate(0xD53354D4Fb7BcE81Cd4F83c457dbd5EF655C9E93,2734 ); _allocate(0x49216a6434B75051e9063E99Bb486bc85B0b0605,1953 ); _allocate(0xD53354D4Fb7BcE81Cd4F83c457dbd5EF655C9E93,1953 ); _allocate(0x4CEa5d86Bb0bBFa77CB452CCBD52e76dEA4dE045,1627 ); _allocate(0xC274362c1E85834Eb8387C18168C01aaEe2B00d7,1562 ); _allocate(0x18A8e216c3406dED40438856B45198B3ce39e522,1367 ); _allocate(0x51B3954e185869FB4cb9D2Bf9Fbd00A22900E800,477 ); } function saleOneAllocationsLocking() private { uint256 lockingPeriod = 24 hours; _allocateLock(0xCCa178a04D83Af193330C7927fb9a42212Fb1C25, 85932, lockingPeriod); _allocateLock(0xD7d7d68E4BDCf85c073485aB7Bfd151B0C019F1F, 39060, lockingPeriod); _allocateLock(0xf470bbfeaB9B0d60e21FBd611C5d569df20704CE, 31248, lockingPeriod); _allocateLock(0x9022BC8774AebC343De33423570b5285981bd9E1, 31248, lockingPeriod); _allocateLock(0xcf9Bb70b2f1aCCb846e8B0C665a1Ab5D5D35cA05, 31248, lockingPeriod); _allocateLock(0xfce0413BAD4E59f55946669E678EccFe87777777, 23436, lockingPeriod); _allocateLock(0xf470bbfeaB9B0d60e21FBd611C5d569df20704CE, 23436, lockingPeriod); _allocateLock(0xfEeA4Cd7a96dCffBDc6d2e6c814eb4544ab62667, 23436, lockingPeriod); _allocateLock(0xb4A0563DE6ABeE9C3C0631FbAE3444F012a40dB5, 19530, lockingPeriod); _allocateLock(0x54a9bB530474d287202Da7f4d5c9756E13f699f3, 15624, lockingPeriod); _allocateLock(0xEad249D58E4ebbFBf4ABbeCc1201bD88E50f7967, 15624, lockingPeriod); _allocateLock(0x3Dd4234DaeefBaBCeAA6068C04C3f75F19aa2cdA, 15624, lockingPeriod); _allocateLock(0x88F7541D87b7f3c88115A5b2387587263c5d4C7E, 11718, lockingPeriod); _allocateLock(0xf3e4D991a20043b6Bd025058CF4d96Fd7501070b, 11718, lockingPeriod); _allocateLock(0xEc315068A71458FB1A6cC063E9BC7369EC41a7a5, 8593, lockingPeriod); _allocateLock(0x54a9bB530474d287202Da7f4d5c9756E13f699f3, 7812, lockingPeriod); _allocateLock(0x0fEB352cfd10314af9abCF4eD03Da9311Bf8bC44, 7812, lockingPeriod); _allocateLock(0xd28932b8d4Be295D4B90b514EFa3E80436d66bEC, 7812, lockingPeriod); _allocateLock(0x268e1fEE56498Cc24758864AA092F870e8220f74, 7812, lockingPeriod); _allocateLock(0xDFF214084Fee648c8e0bc0838C1fa5E8548F58aC, 7812, lockingPeriod); _allocateLock(0x4356DdB30910c1f9b3Aa1e6A60111CE9802B6dF9, 7812, lockingPeriod); _allocateLock(0x863A3bD6f28f4F4A131c88708dA91076fDC362C7, 7812, lockingPeriod); _allocateLock(0x3F79B63823E435FaF08A95e0973b389333B19b99, 7812, lockingPeriod); _allocateLock(0x8F70b3aC45A6896532FB90B992D5B7827bA88d3C, 7812, lockingPeriod); _allocateLock(0xEc315068A71458FB1A6cC063E9BC7369EC41a7a5, 6640, lockingPeriod); _allocateLock(0x138EcD97Da1C9484263BfADDc1f3D6AE2a435bCb, 6250, lockingPeriod); _allocateLock(0x53A07d3c1Fdc58c0Cfd2c96817D9537A9E113dd4, 5468, lockingPeriod); _allocateLock(0xCEC0971e55A4C39e3e2C4d8f175CC6e53c138B0A, 4297, lockingPeriod); _allocateLock(0xBA682E593784f7654e4F92D58213dc495f229Eec, 3906, lockingPeriod); _allocateLock(0x9B9e35C223B39f908A036E41011D9E3aDb06ae0B, 3906, lockingPeriod); _allocateLock(0xBA98b69a140c078746219D0bBf0bb3b923483374, 3906, lockingPeriod); _allocateLock(0x34c4E14243a95b148534f894FCe86c61bC9F731a, 3906, lockingPeriod); _allocateLock(0x9A61567A3e3c5b47DFFB0670C629A40533Eb84d5, 3906, lockingPeriod); _allocateLock(0xda90dDbbdd4e0237C6889367c1556179c817680B, 3567, lockingPeriod); _allocateLock(0x329318Ca294A2d127e43058A7b23ED514B503d76, 2734, lockingPeriod); _allocateLock(0x7B3fC9597f146F0A80FC26dB0DdF62C04ea89740, 2578, lockingPeriod); _allocateLock(0xb6eC0d0172BC4Cff8fF669b543e03c2c8B64Fc5E, 2344, lockingPeriod); _allocateLock(0x53A07d3c1Fdc58c0Cfd2c96817D9537A9E113dd4, 2344, lockingPeriod); } function saleTwoAllocationsLocking() private { uint256 lockingPeriod = 12 hours; _allocateLock(0xc77c3EfB55bd7b0E44c13EB27eb33c98597f0a68, 16758, lockingPeriod); _allocateLock(0x9E817382A12D2b1D15246c4d383bEB8171BCdfA9, 13965, lockingPeriod); _allocateLock(0xfF6735CFf3DFED5d68dC3DbeBb0d34c5e815BA09, 11172, lockingPeriod); _allocateLock(0x5400087152e436C7C22883d01911868A3C892551, 7820, lockingPeriod); _allocateLock(0x974896E96219Dd508100f2Ad58921290655072aD, 5586, lockingPeriod); _allocateLock(0x0fEB352cfd10314af9abCF4eD03Da9311Bf8bC44, 5586, lockingPeriod); _allocateLock(0x268e1fEE56498Cc24758864AA092F870e8220f74, 5586, lockingPeriod); _allocateLock(0xC274362c1E85834Eb8387C18168C01aaEe2B00d7, 4469, lockingPeriod); _allocateLock(0x93935316db093A8665E91EE932591F76bf8E5295, 3631, lockingPeriod); _allocateLock(0x8bdBF4B19cb840e9Ac9B1eFFc2BfAd47591B5bF2, 2793, lockingPeriod); } function _allocateLock(address user, uint256 tokens, uint256 lockingPeriod) private{ uint256 startTime = 1599253200; // 4 sep walletsLocking[user].directRelease = true; walletsLocking[user].lockedTokens = tokens * 10 ** (decimals); walletsLocking[user].cliff = startTime.add(lockingPeriod); _allocate(user, tokens); } function _allocate(address user, uint256 tokens) private { balances[user] = balances[user].add(tokens * 10 ** (decimals)); emit Transfer(address(0),user, tokens * 10 ** (decimals)); } /** ERC20Interface function's implementation **/ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0), "Transfer to address 0 not allowed"); require(balances[msg.sender] >= tokens, "SENDER: insufficient balance"); if (walletsLocking[msg.sender].lockedTokens > 0 ){ if(walletsLocking[msg.sender].directRelease) directRelease(msg.sender); else checkTime(msg.sender); } require(balances[msg.sender].sub(tokens) >= walletsLocking[msg.sender].lockedTokens, "Please wait for tokens to be released"); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance // prevent transfer to 0x0, use burn instead require(address(to) != address(0), "Transfer to address 0 not allowed"); require(address(from) != address(0), "Transfer from address 0 not allowed"); require(balances[from] >= tokens, "SENDER: Insufficient balance"); if (walletsLocking[from].lockedTokens > 0){ if(walletsLocking[from].directRelease) directRelease(from); else checkTime(from); } require(balances[from].sub(tokens) >= walletsLocking[from].lockedTokens, "Please wait for tokens to be released"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // @dev Internal function that burns an amount of the token from a given account // @param _amount The amount that will be burnt // @param _account The tokens to burn from // can be used from account owner or contract owner // ------------------------------------------------------------------------ function burnTokens(uint256 _amount, address _account) public { require(msg.sender == _account || msg.sender == owner, "UnAuthorized"); require(balances[_account] >= _amount, "Insufficient account balance"); _totalSupply = _totalSupply.sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } function directRelease(address _wallet) private{ if(block.timestamp > walletsLocking[_wallet].cliff){ walletsLocking[_wallet].lockedTokens = 0; } } function checkTime(address _wallet) private { // if cliff is applied if(block.timestamp > walletsLocking[_wallet].cliff){ uint256 timeSpanned = (now.sub(walletsLocking[_wallet].lastVisit)).div(walletsLocking[_wallet].releasePeriod); // if release period is passed if (timeSpanned >= 1){ uint256 released = timeSpanned.mul(walletsLocking[_wallet].releasePercentage); if (released > walletsLocking[_wallet].lockedTokens){ released = walletsLocking[_wallet].lockedTokens; } walletsLocking[_wallet].lastVisit = now; walletsLocking[_wallet].lockedTokens = walletsLocking[_wallet].lockedTokens.sub(released); } } } }
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ prevent transfer to 0x0, use burn instead
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(address(to) != address(0), "Transfer to address 0 not allowed"); require(address(from) != address(0), "Transfer from address 0 not allowed"); require(balances[from] >= tokens, "SENDER: Insufficient balance"); if (walletsLocking[from].lockedTokens > 0){ if(walletsLocking[from].directRelease) directRelease(from); else checkTime(from); } require(balances[from].sub(tokens) >= walletsLocking[from].lockedTokens, "Please wait for tokens to be released"); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; }
945,348
./full_match/1/0xc600727f1Ce705436734F2367e7FC449da5fB3a6/sources/contracts/tokens/AutoCoinageSnapshot2.sol
@inheritdoc IAutoCoinageSnapshot2
function balanceOfAt(address layer2, address account, uint256 snapshotId) public view override returns (uint256) { if (snapshotId > 0) { (bool snapshotted1, uint256 balances, uint256 refactoredCounts, uint256 remains) = _balanceOfAt(layer2, account, snapshotId); (bool snapshotted2, uint256 factors, uint256 refactorCounts) = _factorAt(layer2, snapshotId); if (snapshotted1 && snapshotted2) { uint256 bal = applyFactor(balances, refactoredCounts, factors, refactorCounts); bal += remains; return bal; return 0; } return 0; } }
9,638,817
./full_match/4/0x838738061C8B1b1557B612eDEf7d94eaFB22E43F/sources/browser/Untitled45.sol
------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account. The spender contract function receiveApproval(...) is then executed ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
791,521
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // ============ Imports ============ import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Base64.sol"; import "ds-test/test.sol"; import "./IEIP2981.sol"; import "./IERC1155WithRoyalty.sol"; /// @notice Error library for centralised error messaging library Errors { string constant invalidCitizenshipId = "Unknown Citizen NFT ID"; } /// @title CitizenNFT /// @author Odysseas Lamtzidis /// @notice An ERC721 NFT that replaces the Citizen NFTs that are issued by the OpenSea Storefront Smart contract. /// This smart contract enables users to either mint a new CitizenNFT or /// "transfer" their Citizen NFTs from the OpenSea smart contract to this one. contract CitizenNFT is ERC1155, Ownable, IERC1155WithRoyalty, IEIP2981, ReentrancyGuard { // We use safemath to avoid under and over flows using SafeMath for uint256; // At the time of writing, a new CitizenNFT costs 0.25 ether. // This variable can change by the appropriate function uint256 private citizenshipStampCostInWei = 250000000000000000; // Internal Ids that are used to differentiate between the different Citizen NFTs uint256 private constant CITIZEN_NFT_ID = 42; uint256 private constant FOUNDING_NFT_ID = 69; uint256 private constant FIRST_NFT_ID = 7; // Events event LogEthDeposit(address); event CitizenLegislatureChanged(string, uint256); event NewCitizen(address, uint256, uint256); event TokenRoyaltySet(uint256 tokenId, address recipient, uint16 bps); event DefaultRoyaltySet(address recipient, uint16 bps); // ERC1155 uint256 private mintedCitizensCounter = 0; uint256 private mintedFoundingCitizensCounter = 0; uint256 private mintedFirstCitizensCounter = 0; // EIP2981 struct TokenRoyalty { address recipient; uint16 bps; } TokenRoyalty public defaultRoyalty; mapping(uint256 => TokenRoyalty) private _tokenRoyalties; // NFT metadata mapping(uint256 => string) private tokenURIs; mapping(uint256 => string) private citizenNFTDescriptions; //Initialisation bool private contractInitialized; uint256 private reservedCitizenships; /// @notice Initialise CitizenNFT smart contract with the appropriate address and ItemIds of the /// Open Sea shared storefront smart contract and the Citizen NFTs that are locked in it. constructor(address _royaltyRecipient, uint16 _royaltyBPS) Ownable() ERC1155("") { defaultRoyalty = TokenRoyalty(_royaltyRecipient, _royaltyBPS); tokenURIs[ CITIZEN_NFT_ID ] = "ipfs://QmRRnuHVwhoYEHsTxzMcGdrCfthKTS66gnfUqDZkv6kbza"; tokenURIs[ FOUNDING_NFT_ID ] = "ipfs://QmSrKL6fhPYU6BbYrV97AJm3aM6naGWZK95QntXXZuGQrF"; tokenURIs[ FIRST_NFT_ID ] = "ipfs://Qmb6VmYiktfvNX3YkLosYwjUM82PcEkr2irZ4PWheYiG2b"; citizenNFTDescriptions[CITIZEN_NFT_ID] = "CityDAO Citizen"; citizenNFTDescriptions[FOUNDING_NFT_ID] = "Founding CityDAO Citizen"; citizenNFTDescriptions[FIRST_NFT_ID] = "CityDAO First Citizen"; contractInitialized = false; reservedCitizenships = 0; } ///@notice Request a new Citizen NFT from the owner of the smart contract. /// You can request any number of NFTs and pay `citizenshipStampCostInWei` per NFT ///@param _citizenNumber Number of Citizen NFTs to request function onlineApplicationForCitizenship(uint256 _citizenNumber) public payable nonReentrant { require( msg.value >= citizenshipStampCostInWei * _citizenNumber, "ser, the state machine needs oil" ); require( this.balanceOf(this.owner(), CITIZEN_NFT_ID) - _citizenNumber > reservedCitizenships, "No available Citizenship" ); _safeTransferFrom( this.owner(), msg.sender, CITIZEN_NFT_ID, _citizenNumber, "" ); } ///@notice Mint new citizenNFTs to an address, usually that of CityDAO. ///@param _to Address to where the NFTs must be minted ///@param _citizenType ID for the Citizen NFT (42 for regular, 69 for founding, 7 for first) ///@param _numberOfCitizens The number of Citizen NFTs to be minted function issueNewCitizenships( address _to, uint256 _citizenType, uint256 _numberOfCitizens ) public onlyOwner { if (_citizenType == 42) { mintedCitizensCounter = mintedCitizensCounter.add( _numberOfCitizens ); } else if (_citizenType == 69) { mintedFoundingCitizensCounter = mintedFoundingCitizensCounter.add( _numberOfCitizens ); } else if (_citizenType == 7) { mintedFirstCitizensCounter = mintedFirstCitizensCounter.add( _numberOfCitizens ); } else { revert(Errors.invalidCitizenshipId); } _mint(_to, _citizenType, _numberOfCitizens, ""); } function initialCitizenship() external onlyOwner { require(contractInitialized == false, "contract initialized already"); issueNewCitizenships(msg.sender, CITIZEN_NFT_ID, 10000); issueNewCitizenships(msg.sender, FOUNDING_NFT_ID, 50); issueNewCitizenships(msg.sender, FIRST_NFT_ID, 1); contractInitialized = true; } /// @notice Change the cost for minting a new regular Citizen NFT /// Can only be called by the owner of the smart contract. function legislateCostOfEntry(uint256 _stampCost) external onlyOwner { citizenshipStampCostInWei = _stampCost; emit CitizenLegislatureChanged("stampCost", _stampCost); } /// @notice Return the current cost of minting a new regular Citizen NFT. function inquireCostOfEntry() external view returns (uint256) { return citizenshipStampCostInWei; } /// @notice Return the number of minted Citizen NFTs function inquireHousingNumbers() external view returns (uint256) { return mintedCitizensCounter; } /// @notice Return the current maximum number of minted Founding Citizen NFTs function inquireAboutHistory() external view returns (uint256) { return mintedFoundingCitizensCounter; } /// @notice Withdraw the funds locked in the smart contract, /// originating from the minting of new regular Citizen NFTs. /// Can only becalled by the owner of the smart contract. function raidTheCoffers() external onlyOwner { uint256 amount = address(this).balance; (bool success, ) = owner().call{value: amount}(""); require(success, "Anti-corruption agencies stopped the transfer"); } function reserveCitizenships(uint256 _numberOfCitizenships) external onlyOwner { reservedCitizenships = _numberOfCitizenships; } function howManyReservedCitizenships() external view returns (uint256) { return reservedCitizenships; } fallback() external payable { emit LogEthDeposit(msg.sender); } receive() external payable { emit LogEthDeposit(msg.sender); } /// @notice Airdrop Citizen NFTs to users. The citizen NFTs must first be minted to the owner address. function awardCitizenship( address[] calldata _awardees, uint256[] calldata _numberOfCitizenships, uint256 _citizenshipType ) external onlyOwner { require( _awardees.length == _numberOfCitizenships.length, "array length not equal" ); address cityDAO = this.owner(); for (uint256 i = 0; i < _awardees.length; i++) { safeTransferFrom( cityDAO, _awardees[i], _citizenshipType, _numberOfCitizenships[i], "" ); } } /// @notice returns the uri metadata. Used by marketplaces and wallets to show the NFT function uri(uint256 _citizenNFTId) public view override returns (string memory) { string memory json = Base64.encode( bytes( string( abi.encodePacked( '{ "name": "', citizenNFTDescriptions[_citizenNFTId], '", ', '"description" : ', '"A Citizen of CityDAO holds governance in the operations and activities of CityDAO.",', '"image": "', tokenURIs[_citizenNFTId], '"' "}" ) ) ) ); return string(abi.encodePacked("data:application/json;base64,", json)); } /// @notice Change the URI of citizen NFTs /// @param _tokenURIs Array of new token URIs /// @param _citizenNFTIds Array of citizen NFT Ids (69 OR 42 OR 7) for the respective URIs function changeURIs( string[] calldata _tokenURIs, uint256[] calldata _citizenNFTIds ) external onlyOwner { for (uint256 i = 0; i < _tokenURIs.length; i++) { tokenURIs[_citizenNFTIds[i]] = _tokenURIs[i]; } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Royalty implementation based on @abbouali // https://github.com/abbouali/sample_erc1155_with_eip2981 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// @dev Define the fee for the token specify /// @param tokenId uint256 token ID to specify /// @param recipient address account that receives the royalties function setTokenRoyalty( uint256 tokenId, address recipient, uint16 bps ) public override onlyOwner { _tokenRoyalties[tokenId] = TokenRoyalty(recipient, bps); emit TokenRoyaltySet(tokenId, recipient, bps); } /// @dev Define the default amount of fee and receive address /// @param recipient address ID account receive royalty /// @param bps uint256 amount of fee (1% == 100) function setDefaultRoyalty(address recipient, uint16 bps) public override onlyOwner { defaultRoyalty = TokenRoyalty(recipient, bps); emit DefaultRoyaltySet(recipient, bps); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155) returns (bool) { return interfaceId == type(IEIP2981).interfaceId || interfaceId == type(IERC1155WithRoyalty).interfaceId || super.supportsInterface(interfaceId); } /// @dev Returns royalty info (address to send fee, and fee to send) /// @param tokenId uint256 ID of the token to display information /// @param value uint256 sold price function royaltyInfo(uint256 tokenId, uint256 value) public view override returns (address, uint256) { if (_tokenRoyalties[tokenId].recipient != address(0)) { return ( _tokenRoyalties[tokenId].recipient, (value * _tokenRoyalties[tokenId].bps) / 10000 ); } if (defaultRoyalty.recipient != address(0) && defaultRoyalty.bps != 0) { return ( defaultRoyalty.recipient, (value * defaultRoyalty.bps) / 10000 ); } return (address(0), 0); } }
Return the number of minted Citizen NFTs
function inquireHousingNumbers() external view returns (uint256) { return mintedCitizensCounter; }
1,764,122
pragma solidity ^0.4.11; /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indiponye this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of Ponie 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } /// @title A facet of PonyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyAccessControl { // This facet controls access control for CryptoPoniesies. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the PonyCore constructor. // // - The CFO: The CFO can withdraw funds from PonyCore and its auction contracts. // // - The COO: The COO can release gen0 Poniesies to auction, and mint promo ponys. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoPoniesies. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBase is PonyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new Ponie comes into existence. This obviously /// includes any time a pony is created through the giveBirth method, but it is also called /// when a new gen0 pony is created. event Birth(address owner, uint256 PonyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a Ponie /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Pony struct. Every pony in CryptoPoniesies is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Pony { // The Pony's genetic code is packed into these 256-bits, the format is // sooper-sekret! A pony's genes never change. uint256 genes; // The timestamp from the block when this pony came into existence. uint64 birthTime; // The minimum timestamp after which this pony can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Pony, set to 0 for gen0 ponys. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion ponys. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire pony for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a pony // is pregnant. Used to retrieve the genetic material for the new // Ponie when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Pony. This starts at zero // for gen0 ponys, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this pony is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this pony. ponys minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other ponys is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indiponying the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a pony /// is bred, encouraging owners not to just keep breeding the same pony over /// and over again. Caps out at one week (a pony can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Pony struct for all Poniesies in existence. The ID /// of each pony is actually an index into this array. Note that ID 0 is a negapony, /// the unPony, the mythical beast that is the parent of all gen0 ponys. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, pony ID 0 is invalid... ;-) Pony[] Poniesies; /// @dev A mapping from pony IDs to the address that owns them. All ponys have /// some valid owner address, even gen0 ponys are created with a non-zero owner. mapping (uint256 => address) public PonyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from PonyIDs to an address that has been approved to call /// transferFrom(). Each Pony can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public PonyIndexToApproved; /// @dev A mapping from PonyIDs to an address that has been approved to use /// this Pony for siring via breedWith(). Each Pony can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of Poniesies. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev Assigns ownership of a specific Pony to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of Ponies is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership PonyIndexToOwner[_tokenId] = _to; // When creating new Ponies _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the Ponie is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete PonyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Pony and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Pony ID of the matron of this pony (zero for gen0) /// @param _sireId The Pony ID of the sire of this pony (zero for gen0) /// @param _generation The generation number of this pony, must be computed by caller. /// @param _genes The Pony's genetic code. /// @param _owner The inital owner of this pony, must be non-zero (except for the unPony, ID 0) function _createPony( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createPony() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New Pony starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Pony memory _Pony = Pony({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newPonieId = Poniesies.push(_Pony) - 1; // It's probably never going to happen, 4 billion ponys is A LOT, but // let's just be 100% sure we never let this happen. require(newPonieId == uint256(uint32(newPonieId))); // emit the birth event Birth( _owner, newPonieId, uint256(_Pony.matronId), uint256(_Pony.sireId), _Pony.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPonieId); return newPonieId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the Poniesies, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the CryptoPoniesies core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyOwnership is PonyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoPonies"; string public constant symbol = "CPT1"; // The contract that will return Pony metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Pony. /// @param _claimant the address we are validating against. /// @param _tokenId Ponie id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return PonyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Pony. /// @param _claimant the address we are confirming Ponie is approved for. /// @param _tokenId Ponie id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return PonyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Poniesies on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { PonyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Poniesies owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Pony to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoPoniesies specifically) or your Pony may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Pony to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Poniesies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of Poniesies // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own pony. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Pony via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Pony that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Pony owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Pony to be transfered. /// @param _to The address that should take ownership of the Pony. Can be any address, /// including the caller. /// @param _tokenId The ID of the Pony to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Poniesies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Poniesies currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return Poniesies.length - 1; } /// @notice Returns the address currently assigned ownership of a given Pony. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = PonyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Pony IDs assigned to an address. /// @param _owner The owner whose Poniesies we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Pony array looking for ponys belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalponys = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all ponys have IDs starting at 1 and increasing // sequentially up to the totalpony count. uint256 ponyId; for (ponyId = 1; ponyId <= totalponys; ponyId++) { if (PonyIndexToOwner[ponyId] == _owner) { result[resultIndex] = ponyId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes 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)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Pony whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } /// @title A facet of PonyCore that manages Pony siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBreeding is PonyOwnership { /// @dev The Pregnant event is fired when two ponys successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant Poniesies. uint256 public pregnantPoniesies; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given Ponie is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Pony _pony) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the pony has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_pony.siringWithId == 0) && (_pony.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = PonyIndexToOwner[_matronId]; address sireOwner = PonyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Pony, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _Ponie A reference to the Pony in storage which needs its timer started. function _triggerCooldown(Pony storage _Ponie) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _Ponie.cooldownEndBlock = uint64((cooldowns[_Ponie.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_Ponie.cooldownIndex < 13) { _Ponie.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Poniesies. /// @param _addr The address that will be able to sire with your Pony. Set to /// address(0) to clear all siring approvals for this Pony. /// @param _sireId A Pony that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Pony is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Pony _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given Ponie is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _PonyId reference the id of the Ponie, any user can inquire about it function isReadyToBreed(uint256 _PonyId) public view returns (bool) { require(_PonyId > 0); Pony storage pony = Poniesies[_PonyId]; return _isReadyToBreed(pony); } /// @dev Checks whether a Pony is currently pregnant. /// @param _PonyId reference the id of the Ponie, any user can inquire about it function isPregnant(uint256 _PonyId) public view returns (bool) { require(_PonyId > 0); // A Pony is pregnant if and only if this field is set return Poniesies[_PonyId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Pony struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Pony struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Pony storage _matron, uint256 _matronId, Pony storage _sire, uint256 _sireId ) private view returns(bool) { // A Pony can't breed with itself! if (_matronId == _sireId) { return false; } // Poniesies can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either pony is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Poniesies can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Pony storage matron = Poniesies[_matronId]; Pony storage sire = Poniesies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two ponys can breed together, including checks for /// ownership and siring approvals. Does NOT check that both ponys are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Pony storage matron = Poniesies[_matronId]; Pony storage sire = Poniesies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { // Grab a reference to the Poniesies from storage. Pony storage sire = Poniesies[_sireId]; Pony storage matron = Poniesies[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a Pony gets pregnant, counter is incremented. pregnantPoniesies++; // Emit the pregnancy event. Pregnant(PonyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } /// @notice Breed a Pony you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your pony pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Pony acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Pony acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Pony on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either pony // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Pony storage matron = Poniesies[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Pony storage sire = Poniesies[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these ponys are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, Pony gets pregnant! _breedWith(_matronId, _sireId); } /// @notice Have a pregnant Pony give birth! /// @param _matronId A Pony ready to give birth. /// @return The Pony ID of the new Ponie. /// @dev Looks at a given Pony and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new Ponie. The new Pony is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new Ponie will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new Ponie always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Pony storage matron = Poniesies[_matronId]; // Check that the matron is a valid pony. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Pony storage sire = Poniesies[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new Ponie! address owner = PonyIndexToOwner[_matronId]; uint256 PonieId = _createPony(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a Pony gives birth counter is decremented. pregnantPoniesies--; // Send the balance fee to the person who made birth happen. msg.sender.send(autoBirthFee); // return the new Ponie's ID return PonieId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multipliponyion can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've alloponyed // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've alloponyed // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the PonyCore contract because all bid methods /// should be wrapped. Also returns the Pony to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the Pony back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of Poniesies /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 Pony sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've alloponyed // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of Poniesies. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract PonyAuction is PonyBreeding { // @notice The auction contract variables are defined in PonyBase to allow // us to refer to them in PonyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of Poniesies. // `siringAuction` refers to the auction for siring rights of Poniesies. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _PonyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createAuction( _PonyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _PonyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToBreed(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createAuction( _PonyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the PonyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// @title all functions related to creating Ponies contract PonyMinting is PonyAuction { // Limits the number of ponys the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of ponys the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo Ponies, up to a limit. Only callable by COO /// @param _genes the encoded genes of the Ponie to be created, any value is accepted /// @param _owner the future owner of the created Ponies. Default to contract COO function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address PonyOwner = _owner; if (PonyOwner == address(0)) { PonyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, PonyOwner); } /// @dev Creates a new gen0 Pony with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 PonyId = _createPony(0, 0, 0, _genes, address(this)); _approve(PonyId, saleAuction); saleAuction.createAuction( PonyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title CryptoPoniesies: Collectible, breedable, and oh-so-adorable ponys on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoPoniesies contract, keeps track of Ponies so they don't wander around and get lost. contract PonyCore is PonyMinting { // This is the main CryptoPoniesies contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Pony ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - PonyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - PonyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - PonyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - PonyBreeding: This file contains the methods necessary to breed ponys together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - PonyAuctions: Here we have the public methods for auctioning or bidding on ponys or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - PonyMinting: This final facet contains the functionality we use for creating new gen0 ponys. // We can make up to 5000 "promo" ponys that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 ponys. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoPoniesies smart contract instance. function PonyCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical Ponie 0 - so we don't have generation-0 parent issues _createPony(0, 0, 0, uint256(-1), address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indiponying that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific Pony. /// @param _id The ID of the Pony of interest. function getPony(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Pony storage pony = Poniesies[_id]; // if this variable is 0 then it's not gestating isGestating = (pony.siringWithId != 0); isReady = (pony.cooldownEndBlock <= block.number); cooldownIndex = uint256(pony.cooldownIndex); nextActionAt = uint256(pony.cooldownEndBlock); siringWithId = uint256(pony.siringWithId); birthTime = uint256(pony.birthTime); matronId = uint256(pony.matronId); sireId = uint256(pony.sireId); generation = uint256(pony.generation); genes = pony.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = this.balance; // Subtract all the currently pregnant Ponies we have, plus 1 of margin. uint256 subtractFees = (pregnantPoniesies + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } }
Checks to see if two ponys can breed together, including checks for ownership and siring approvals. Does NOT check that both ponys are ready for breeding (i.e. breedWith could still fail until the cooldowns are finished). TODO: Shouldn't this check pregnancy and cooldowns?!? _matronId The ID of the proposed matron. _sireId The ID of the proposed sire.
function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Pony storage matron = Poniesies[_matronId]; Pony storage sire = Poniesies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); }
11,693,696
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract CryptoMonkeyChars is ERC721Enumerable, ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter public _tokenIds; //mapping to nft attributes struct CharAttributes { uint8 monkeyType; uint8 charLevel; uint256 mintTime; bool openedBox; uint16 boxType; } mapping (uint256 => CharAttributes) public tokensAttributes; //call to ERC20 contract address public tokenAddress; //define costs of interactions mapping (uint16 => uint256) public mintCost; uint256 public levelUpCost; //base URI location string public baseUriString; constructor( address _tokenAddress, uint256 _mintCostBasic, uint256 _mintCostRare, uint256 _mintCostLegendary, uint256 _levelUpCost, string memory _baseUriString ) ERC721("CryptoMonkeys", "CMONKEYS") { //setup owner variables tokenAddress = _tokenAddress; mintCost[1] = _mintCostBasic; mintCost[2] = _mintCostRare; mintCost[3] = _mintCostLegendary; levelUpCost = _levelUpCost; baseUriString = _baseUriString; } //override attributes of base classes that collude function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _baseURI() internal view override returns (string memory) { return baseUriString; } //end override /** * @dev Secton to create actual nft functionalities * will create: * - randomness source V * - function to set attributes of each minted nft V * - nft minting function V * - nft levelling up function V * - owner interface to change cost of minting V * - owner interface to change cost of upgrading V * - owner interface to change base url of tokens V */ /** * @dev source of randomness for contract */ function randomElement(uint256 tokenId) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, msg.sender, _tokenIds.current(), tokenId))); } /** * @dev mapping of different monkey types */ function _getMonkeyType(uint256 _seed, uint16 _probabilityMapping) internal pure returns (uint8) { //declare rarities uint8 commom; uint8 rare; uint8 epic; uint8 legendary; //adjust to _probabilityMapping if (_probabilityMapping == 1) { commom = 68; rare = 22; epic = 8; legendary = 2; } else if (_probabilityMapping == 2) { commom = 30; rare = 40; epic = 20; legendary = 10; } else if (_probabilityMapping == 3) { commom = 0; rare = 40; epic = 40; legendary = 20; } //deliver result if (_seed < commom) { return uint8( (_seed % 4) + 1 ); } else if (_seed < (commom + rare) ) { return uint8( (_seed % 3) + 5 ); } else if (_seed < (commom + rare + epic) ) { return uint8( (_seed % 2) + 8 ); } else if (_seed < (commom + rare + epic + legendary) ) { return uint8( (_seed % 2) + 10 ); } else { revert("Failure in random selection method"); } } /** * @dev Sets all of the tokens relevant attributes (monkey tipe, level, * mintTime and URI). * * @param tokenId id of created token * @param _probabilityMapping id of the probebility mapping to be used accordingly to type of * box purchased by player * Requirements: * * - `tokenId` must exist. * - `tokenId` must not be a mapping key already */ function _setTokenAttributes(uint256 tokenId, uint16 _probabilityMapping) internal { uint8 _monkeyType = _getMonkeyType(randomElement(tokenId) % 100, _probabilityMapping); tokensAttributes[tokenId] = CharAttributes({ monkeyType: _monkeyType, charLevel: 1, mintTime: block.timestamp, openedBox: false, boxType: _probabilityMapping }); _setTokenURI(tokenId, string(abi.encodePacked("/", Strings.toString(_monkeyType), ".png"))); } /** * @dev mints new nft and burns the price * * @param recipient address that wishes to mint the nft * need to add support for multiple box types and prices */ function mintNft(address recipient, uint16 _probabilityMapping) public { require(_probabilityMapping == 1 || _probabilityMapping == 2 || _probabilityMapping == 3, "CryptoMonkeyChars: mintNft: _probabilityMapping must belong to uint16[1, 2, 3]"); ERC20Burnable tokenContract = ERC20Burnable(tokenAddress); tokenContract.burnFrom(msg.sender, mintCost[_probabilityMapping]); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(recipient, newItemId); _setTokenAttributes(newItemId, _probabilityMapping); } /** * @dev upgrades nft to level 2 * * @param recipient owner of the asset. Must have granted allowance for contract and * must be the caller * @param nftIndex index of the asset * user will pay upgrade price by burning tokens and nft will be upgraded to level 2 */ function upgradeNft(address recipient, uint256 nftIndex) public { require(ownerOf(nftIndex) == recipient, "CryptoMonkeysChars: owner is not recipient"); require(ownerOf(nftIndex) == msg.sender, "CryptoMonkeysChars: owner is not sender"); require(tokensAttributes[nftIndex].charLevel == 1, "CryptoMonkeysChars: char is already level 2"); ERC20Burnable tokenContract = ERC20Burnable(tokenAddress); tokenContract.burnFrom(recipient, levelUpCost); tokensAttributes[nftIndex].charLevel = 2; } function getNftData(uint256 nftIndex) public view returns (uint8, uint8, uint256, bool, uint16) { return (tokensAttributes[nftIndex].monkeyType, tokensAttributes[nftIndex].charLevel, tokensAttributes[nftIndex].mintTime, tokensAttributes[nftIndex].openedBox, tokensAttributes[nftIndex].boxType); } /** * @dev owner private functions to set contract attributes */ function setTokenAddress(address _address) public onlyOwner { tokenAddress = _address; } function setMintCost(uint256 _cost1, uint256 _cost2, uint256 _cost3) public onlyOwner { mintCost[1] = _cost1; mintCost[2] = _cost2; mintCost[3] = _cost3; } function setLevelUpCost(uint256 _cost) public onlyOwner { levelUpCost = _cost; } function setBaseUriString(string memory _baseUriString) public onlyOwner { baseUriString = _baseUriString; } }
Sets all of the tokens relevant attributes (monkey tipe, level, mintTime and URI). tokenId id of created token _probabilityMapping id of the probebility mapping to be used accordingly to type of box purchased by player Requirements: - `tokenId` must exist. - `tokenId` must not be a mapping key already/
function _setTokenAttributes(uint256 tokenId, uint16 _probabilityMapping) internal { uint8 _monkeyType = _getMonkeyType(randomElement(tokenId) % 100, _probabilityMapping); tokensAttributes[tokenId] = CharAttributes({ monkeyType: _monkeyType, charLevel: 1, mintTime: block.timestamp, openedBox: false, boxType: _probabilityMapping }); _setTokenURI(tokenId, string(abi.encodePacked("/", Strings.toString(_monkeyType), ".png"))); }
12,558,569
./partial_match/40/0x3D2c6bCED5f50f5412234b87fF0B445aBA4d10e9/sources/MasterChef.sol
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.accZAPPerShare).div(1e12).sub(user.rewardDebt); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accZAPPerShare).div(1e12); if(pending > 0) { safeZAPTransfer(msg.sender, pending); } pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
8,827,650
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 virtual override returns (address) { return _roleMembers[role].at(index); } /** * @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 virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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 onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } 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 virtual 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 virtual { 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 virtual 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()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (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 proxied contracts do not make use of 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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [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 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/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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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.1 (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 onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // 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 (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 EnumerableSetUpgradeable { // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @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; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { Token } from "../../token/Token.sol"; import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol"; import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol"; /** * @dev Flash-loan recipient interface */ interface IFlashLoanRecipient { /** * @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee */ function onFlashLoan( address caller, IERC20 erc20Token, uint256 amount, uint256 feeAmount, bytes memory data ) external; } /** * @dev Bancor Network interface */ interface IBancorNetwork is IUpgradeable { /** * @dev returns the set of all valid pool collections */ function poolCollections() external view returns (IPoolCollection[] memory); /** * @dev returns the most recent collection that was added to the pool collections set for a specific type */ function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection); /** * @dev returns the set of all liquidity pools */ function liquidityPools() external view returns (Token[] memory); /** * @dev returns the respective pool collection for the provided pool */ function collectionByPool(Token pool) external view returns (IPoolCollection); /** * @dev returns whether the pool is valid */ function isPoolValid(Token pool) external view returns (bool); /** * @dev creates a new pool * * requirements: * * - the pool doesn't already exist */ function createPool(uint16 poolType, Token token) external; /** * @dev creates new pools * * requirements: * * - none of the pools already exists */ function createPools(uint16 poolType, Token[] calldata tokens) external; /** * @dev migrates a list of pools between pool collections * * notes: * * - invalid or incompatible pools will be skipped gracefully */ function migratePools(Token[] calldata pools) external; /** * @dev deposits liquidity for the specified provider and returns the respective pool token amount * * requirements: * * - the caller must have approved the network to transfer the tokens on its behalf (except for in the * native token case) */ function depositFor( address provider, Token pool, uint256 tokenAmount ) external payable returns (uint256); /** * @dev deposits liquidity for the current provider and returns the respective pool token amount * * requirements: * * - the caller must have approved the network to transfer the tokens on its behalf (except for in the * native token case) */ function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256); /** * @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit * request and returns the respective pool token amount * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function depositForPermitted( address provider, Token pool, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the * respective pool token amount * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function depositPermitted( Token pool, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev initiates liquidity withdrawal * * requirements: * * - the caller must have approved the contract to transfer the pool token amount on its behalf */ function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256); /** * @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function initWithdrawalPermitted( IPoolToken poolToken, uint256 poolTokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev cancels a withdrawal request * * requirements: * * - the caller must have already initiated a withdrawal and received the specified id */ function cancelWithdrawal(uint256 id) external; /** * @dev withdraws liquidity and returns the withdrawn amount * * requirements: * * - the provider must have already initiated a withdrawal and received the specified id * - the specified withdrawal request is eligible for completion * - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT * liquidity */ function withdraw(uint256 id) external returns (uint256); /** * @dev performs a trade by providing the input source amount * * requirements: * * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the * native token case) */ function tradeBySourceAmount( Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary ) external payable; /** * @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an * EIP2612 permit request * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function tradeBySourceAmountPermitted( Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev performs a trade by providing the output target amount * * requirements: * * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the * native token case) */ function tradeByTargetAmount( Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary ) external payable; /** * @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an * EIP2612 permit request and returns the target amount and fee * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function tradeByTargetAmountPermitted( Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev provides a flash-loan * * requirements: * * - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address */ function flashLoan( Token token, uint256 amount, IFlashLoanRecipient recipient, bytes calldata data ) external; /** * @dev deposits liquidity during a migration */ function migrateLiquidity( Token token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount ) external payable; /** * @dev withdraws pending network fees * * requirements: * * - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege */ function withdrawNetworkFees(address recipient) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol"; import { Pool, PoolLiquidity, IPoolCollection, AverageRate } from "./interfaces/IPoolCollection.sol"; import { IPoolToken } from "./interfaces/IPoolToken.sol"; import { IPoolMigrator } from "./interfaces/IPoolMigrator.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Fraction } from "../utility/FractionLibrary.sol"; import { Upgradeable } from "../utility/Upgradeable.sol"; import { Token } from "../token/Token.sol"; import { Utils, InvalidPool, InvalidPoolCollection } from "../utility/Utils.sol"; interface IPoolCollectionBase { function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external; } interface IPoolCollectionV1 is IPoolCollectionBase { struct PoolLiquidityV1 { uint128 bntTradingLiquidity; // the BNT trading liquidity uint128 baseTokenTradingLiquidity; // the base token trading liquidity uint256 stakedBalance; // the staked balance } struct PoolV1 { IPoolToken poolToken; // the pool token of a given pool uint32 tradingFeePPM; // the trading fee (in units of PPM) bool tradingEnabled; // whether trading is enabled bool depositingEnabled; // whether depositing is enabled AverageRate averageRate; // the recent average rate uint256 depositLimit; // the deposit limit PoolLiquidityV1 liquidity; // the overall liquidity in the pool } function poolData(Token token) external view returns (PoolV1 memory); } /** * @dev Pool Migrator contract */ contract PoolMigrator is IPoolMigrator, Upgradeable, Utils { error UnsupportedVersion(); IPoolCollection private constant INVALID_POOL_COLLECTION = IPoolCollection(address(0)); // the network contract IBancorNetwork private immutable _network; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 0] private __gap; /** * @dev triggered when an existing pool is migrated between pool collections */ event PoolMigrated(Token indexed pool, IPoolCollection prevPoolCollection, IPoolCollection newPoolCollection); /** * @dev a "virtual" constructor that is only used to set immutable state variables */ constructor(IBancorNetwork initNetwork) validAddress(address(initNetwork)) { _network = initNetwork; } /** * @dev fully initializes the contract and its parents */ function initialize() external initializer { __PoolMigrator_init(); } // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __PoolMigrator_init() internal onlyInitializing { __Upgradeable_init(); __PoolMigrator_init_unchained(); } /** * @dev performs contract-specific initialization */ function __PoolMigrator_init_unchained() internal onlyInitializing {} // solhint-enable func-name-mixedcase /** * @inheritdoc Upgradeable */ function version() public pure override(IVersioned, Upgradeable) returns (uint16) { return 1; } /** * @inheritdoc IPoolMigrator */ function migratePool(Token pool) external only(address(_network)) returns (IPoolCollection) { if (address(pool) == address(0)) { revert InvalidPool(); } // get the pool collection that this pool exists in IPoolCollection prevPoolCollection = _network.collectionByPool(pool); if (address(prevPoolCollection) == address(0)) { revert InvalidPool(); } // get the latest pool collection corresponding to its type and ensure that a migration is necessary // note that it's currently not possible to add two pool collections with the same version or type uint16 poolType = prevPoolCollection.poolType(); IPoolCollection newPoolCollection = _network.latestPoolCollection(poolType); if (address(newPoolCollection) == address(prevPoolCollection)) { revert InvalidPoolCollection(); } // migrate all relevant values based on a historical collection version into the new pool collection if (prevPoolCollection.version() == 1) { _migrateFromV1(pool, IPoolCollectionV1(address(prevPoolCollection)), newPoolCollection); emit PoolMigrated({ pool: pool, prevPoolCollection: prevPoolCollection, newPoolCollection: newPoolCollection }); return newPoolCollection; } revert UnsupportedVersion(); } /** * @dev migrates a V1 pool to the latest pool version */ function _migrateFromV1( Token pool, IPoolCollectionV1 sourcePoolCollection, IPoolCollection targetPoolCollection ) private { IPoolCollectionV1.PoolV1 memory data = sourcePoolCollection.poolData(pool); // since the latest pool collection is also v1, currently not additional pre- or post-processing is needed Pool memory newData = Pool({ poolToken: data.poolToken, tradingFeePPM: data.tradingFeePPM, tradingEnabled: data.tradingEnabled, depositingEnabled: data.depositingEnabled, averageRate: data.averageRate, depositLimit: data.depositLimit, liquidity: PoolLiquidity({ bntTradingLiquidity: data.liquidity.bntTradingLiquidity, baseTokenTradingLiquidity: data.liquidity.baseTokenTradingLiquidity, stakedBalance: data.liquidity.stakedBalance }) }); sourcePoolCollection.migratePoolOut(pool, targetPoolCollection); targetPoolCollection.migratePoolIn(pool, newData); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { Fraction112 } from "../../utility/FractionLibrary.sol"; import { Token } from "../../token/Token.sol"; import { IPoolToken } from "./IPoolToken.sol"; struct PoolLiquidity { uint128 bntTradingLiquidity; // the BNT trading liquidity uint128 baseTokenTradingLiquidity; // the base token trading liquidity uint256 stakedBalance; // the staked balance } struct AverageRate { uint32 blockNumber; Fraction112 rate; } struct Pool { IPoolToken poolToken; // the pool token of the pool uint32 tradingFeePPM; // the trading fee (in units of PPM) bool tradingEnabled; // whether trading is enabled bool depositingEnabled; // whether depositing is enabled AverageRate averageRate; // the recent average rate uint256 depositLimit; // the deposit limit PoolLiquidity liquidity; // the overall liquidity in the pool } struct WithdrawalAmounts { uint256 totalAmount; uint256 baseTokenAmount; uint256 bntAmount; } // trading enabling/disabling reasons uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0; uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1; uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2; struct TradeAmountAndFee { uint256 amount; // the source/target amount (depending on the context) resulting from the trade uint256 tradingFeeAmount; // the trading fee amount uint256 networkFeeAmount; // the network fee amount (always in units of BNT) } /** * @dev Pool Collection interface */ interface IPoolCollection is IVersioned { /** * @dev returns the type of the pool */ function poolType() external pure returns (uint16); /** * @dev returns the default trading fee (in units of PPM) */ function defaultTradingFeePPM() external view returns (uint32); /** * @dev returns all the pools which are managed by this pool collection */ function pools() external view returns (Token[] memory); /** * @dev returns the number of all the pools which are managed by this pool collection */ function poolCount() external view returns (uint256); /** * @dev returns whether a pool is valid */ function isPoolValid(Token pool) external view returns (bool); /** * @dev returns specific pool's data */ function poolData(Token pool) external view returns (Pool memory); /** * @dev returns the overall liquidity in the pool */ function poolLiquidity(Token pool) external view returns (PoolLiquidity memory); /** * @dev returns the pool token of the pool */ function poolToken(Token pool) external view returns (IPoolToken); /** * @dev converts the specified pool token amount to the underlying base token amount */ function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256); /** * @dev converts the specified underlying base token amount to pool token amount */ function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256); /** * @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified * amount */ function poolTokenAmountToBurn( Token pool, uint256 tokenAmountToDistribute, uint256 protocolPoolTokenAmount ) external view returns (uint256); /** * @dev creates a new pool * * requirements: * * - the caller must be the network contract * - the pool should have been whitelisted * - the pool isn't already defined in the collection */ function createPool(Token token) external; /** * @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount * * requirements: * * - the caller must be the network contract * - assumes that the base token has been already deposited in the vault */ function depositFor( bytes32 contextId, address provider, Token pool, uint256 tokenAmount ) external returns (uint256); /** * @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount * * requirements: * * - the caller must be the network contract * - the caller must have approved the collection to transfer/burn the pool token amount on its behalf */ function withdraw( bytes32 contextId, address provider, Token pool, uint256 poolTokenAmount ) external returns (uint256); /** * @dev returns the amounts that would be returned if the position is currently withdrawn, * along with the breakdown of the base token and the BNT compensation */ function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory); /** * @dev performs a trade by providing the source amount and returns the target amount and the associated fee * * requirements: * * - the caller must be the network contract */ function tradeBySourceAmount( bytes32 contextId, Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount ) external returns (TradeAmountAndFee memory); /** * @dev performs a trade by providing the target amount and returns the required source amount and the associated fee * * requirements: * * - the caller must be the network contract */ function tradeByTargetAmount( bytes32 contextId, Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount ) external returns (TradeAmountAndFee memory); /** * @dev returns the output amount and fee when trading by providing the source amount */ function tradeOutputAndFeeBySourceAmount( Token sourceToken, Token targetToken, uint256 sourceAmount ) external view returns (TradeAmountAndFee memory); /** * @dev returns the input amount and fee when trading by providing the target amount */ function tradeInputAndFeeByTargetAmount( Token sourceToken, Token targetToken, uint256 targetAmount ) external view returns (TradeAmountAndFee memory); /** * @dev notifies the pool of accrued fees * * requirements: * * - the caller must be the network contract */ function onFeesCollected(Token pool, uint256 feeAmount) external; /** * @dev migrates a pool to this pool collection * * requirements: * * - the caller must be the pool migrator contract */ function migratePoolIn(Token pool, Pool calldata data) external; /** * @dev migrates a pool from this pool collection * * requirements: * * - the caller must be the pool migrator contract */ function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IPoolCollection } from "./IPoolCollection.sol"; /** * @dev Pool Migrator interface */ interface IPoolMigrator is IVersioned { /** * @dev migrates a pool and returns the new pool collection it exists in * * notes: * * - invalid or incompatible pools will be skipped gracefully * * requirements: * * - the caller must be the network contract */ function migratePool(Token pool) external returns (IPoolCollection); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol"; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IOwned } from "../../utility/interfaces/IOwned.sol"; /** * @dev Pool Token interface */ interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable { /** * @dev returns the address of the reserve token */ function reserveToken() external view returns (Token); /** * @dev increases the token supply and sends the new tokens to the given account * * requirements: * * - the caller must be the owner of the contract */ function mint(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions, * but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract */ interface Token { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev burnable ERC20 interface */ interface IERC20Burnable { /** * @dev Destroys tokens from the caller. */ function burn(uint256 amount) external; /** * @dev Destroys tokens from a recipient, deducting from the caller's allowance * * requirements: * * - the caller must have allowance for recipient's tokens of at least the specified amount */ function burnFrom(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; uint32 constant PPM_RESOLUTION = 1000000; // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; struct Fraction { uint256 n; uint256 d; } struct Fraction112 { uint112 n; uint112 d; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Fraction, Fraction112 } from "./Fraction.sol"; import { MathEx } from "./MathEx.sol"; // solhint-disable-next-line func-visibility function zeroFraction() pure returns (Fraction memory) { return Fraction({ n: 0, d: 1 }); } // solhint-disable-next-line func-visibility function zeroFraction112() pure returns (Fraction112 memory) { return Fraction112({ n: 0, d: 1 }); } /** * @dev this library provides a set of fraction operations */ library FractionLibrary { /** * @dev returns whether a standard fraction is valid */ function isValid(Fraction memory fraction) internal pure returns (bool) { return fraction.d != 0; } /** * @dev returns whether a standard fraction is positive */ function isPositive(Fraction memory fraction) internal pure returns (bool) { return isValid(fraction) && fraction.n != 0; } /** * @dev returns whether a 112-bit fraction is valid */ function isValid(Fraction112 memory fraction) internal pure returns (bool) { return fraction.d != 0; } /** * @dev returns whether a 112-bit fraction is positive */ function isPositive(Fraction112 memory fraction) internal pure returns (bool) { return isValid(fraction) && fraction.n != 0; } /** * @dev reduces a standard fraction to a 112-bit fraction */ function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) { Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max); return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) }); } /** * @dev expands a 112-bit fraction to a standard fraction */ function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) { return Fraction({ n: fraction.n, d: fraction.d }); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { Fraction } from "./Fraction.sol"; import { PPM_RESOLUTION } from "./Constants.sol"; uint256 constant ONE = 1 << 127; struct Uint512 { uint256 hi; // 256 most significant bits uint256 lo; // 256 least significant bits } struct Sint256 { uint256 value; bool isNeg; } /** * @dev this library provides a set of complex math operations */ library MathEx { error Overflow(); /** * @dev returns `e ^ f`, where `e` is Euler's number and `f` is the input exponent: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function exp(Fraction memory f) internal pure returns (Fraction memory) { uint256 x = MathEx.mulDivF(ONE, f.n, f.d); uint256 y; uint256 z; uint256 n; if (x >= (ONE << 4)) { revert Overflow(); } unchecked { z = y = x % (ONE >> 3); // get the input modulo 2^(-3) z = (z * y) / ONE; n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / ONE; n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / ONE; n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / ONE; n += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / ONE; n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / ONE; n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / ONE; n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / ONE; n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / ONE; n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / ONE; n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / ONE; n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / ONE; n += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / ONE; n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / ONE; n += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / ONE; n += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / ONE; n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / ONE; n += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / ONE; n += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / ONE; n += z * 0x0000000000000001; // add y^20 * (20! / 20!) n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & (ONE >> 3)) != 0) n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & (ONE >> 2)) != 0) n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & (ONE >> 1)) != 0) n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & (ONE << 0)) != 0) n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & (ONE << 1)) != 0) n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & (ONE << 2)) != 0) n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & (ONE << 3)) != 0) n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) } return Fraction({ n: n, d: ONE }); } /** * @dev returns a fraction with reduced components */ function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) { uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max); return Fraction({ n: fraction.n / scale, d: fraction.d / scale }); } /** * @dev returns the weighted average of two fractions */ function weightedAverage( Fraction memory fraction1, Fraction memory fraction2, uint256 weight1, uint256 weight2 ) internal pure returns (Fraction memory) { return Fraction({ n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2, d: fraction1.d * fraction2.d * (weight1 + weight2) }); } /** * @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range * for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base` */ function isInRange( Fraction memory baseSample, Fraction memory offsetSample, uint32 maxDeviationPPM ) internal pure returns (bool) { Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM)); Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION); Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM)); return lte512(min, mid) && lte512(mid, max); } /** * @dev returns an `Sint256` positive representation of an unsigned integer */ function toPos256(uint256 n) internal pure returns (Sint256 memory) { return Sint256({ value: n, isNeg: false }); } /** * @dev returns an `Sint256` negative representation of an unsigned integer */ function toNeg256(uint256 n) internal pure returns (Sint256 memory) { return Sint256({ value: n, isNeg: true }); } /** * @dev returns the largest integer smaller than or equal to `x * y / z` */ function mulDivF( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256) { Uint512 memory xy = mul512(x, y); // if `x * y < 2 ^ 256` if (xy.hi == 0) { return xy.lo / z; } // assert `x * y / z < 2 ^ 256` if (xy.hi >= z) { revert Overflow(); } uint256 m = _mulMod(x, y, z); // `m = x * y % z` Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)` // if `n < 2 ^ 256` if (n.hi == 0) { return n.lo / z; } uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p` uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256` return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z` } /** * @dev returns the smallest integer larger than or equal to `x * y / z` */ function mulDivC( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256) { uint256 w = mulDivF(x, y, z); if (_mulMod(x, y, z) > 0) { if (w >= type(uint256).max) { revert Overflow(); } return w + 1; } return w; } /** * @dev returns the maximum of `n1 - n2` and 0 */ function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) { return n1 > n2 ? n1 - n2 : 0; } /** * @dev returns the value of `x > y` */ function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo); } /** * @dev returns the value of `x < y` */ function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo); } /** * @dev returns the value of `x >= y` */ function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return !lt512(x, y); } /** * @dev returns the value of `x <= y` */ function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return !gt512(x, y); } /** * @dev returns the value of `x * y` */ function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) { uint256 p = _mulModMax(x, y); uint256 q = _unsafeMul(x, y); if (p >= q) { return Uint512({ hi: p - q, lo: q }); } return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q }); } /** * @dev returns the value of `x - y`, given that `x >= y` */ function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) { if (x.lo >= y) { return Uint512({ hi: x.hi, lo: x.lo - y }); } return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) }); } /** * @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n` */ function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) { uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)` return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)` } /** * @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2` */ function _inv256(uint256 d) private pure returns (uint256) { // approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method uint256 x = 1; for (uint256 i = 0; i < 8; i++) { x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256` } return x; } /** * @dev returns `(x + y) % 2 ^ 256` */ function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x + y; } } /** * @dev returns `(x - y) % 2 ^ 256` */ function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x - y; } } /** * @dev returns `(x * y) % 2 ^ 256` */ function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x * y; } } /** * @dev returns `x * y % (2 ^ 256 - 1)` */ function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) { return mulmod(x, y, type(uint256).max); } /** * @dev returns `x * y % z` */ function _mulMod( uint256 x, uint256 y, uint256 z ) private pure returns (uint256) { return mulmod(x, y, z); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import { IUpgradeable } from "./interfaces/IUpgradeable.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides common utilities for upgradeable contracts */ abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable { error AlreadyInitialized(); // the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract // upgrades bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 1] private __gap; // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __Upgradeable_init() internal onlyInitializing { __AccessControl_init(); __Upgradeable_init_unchained(); } /** * @dev performs contract-specific initialization */ function __Upgradeable_init_unchained() internal onlyInitializing { _initializations = 1; // set up administrative roles _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); // allow the deployer to initially be the admin of the contract _setupRole(ROLE_ADMIN, msg.sender); } // solhint-enable func-name-mixedcase modifier onlyAdmin() { _hasRole(ROLE_ADMIN, msg.sender); _; } modifier onlyRoleMember(bytes32 role) { _hasRole(role, msg.sender); _; } function version() public view virtual override returns (uint16); /** * @dev returns the admin role */ function roleAdmin() external pure returns (bytes32) { return ROLE_ADMIN; } /** * @dev performs post-upgrade initialization * * requirements: * * - this must can be called only once per-upgrade */ function postUpgrade(bytes calldata data) external { uint16 initializations = _initializations + 1; if (initializations != version()) { revert AlreadyInitialized(); } _initializations = initializations; _postUpgrade(data); } /** * @dev an optional post-upgrade callback that can be implemented by child contracts */ function _postUpgrade( bytes calldata /* data */ ) internal virtual {} function _hasRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert AccessDenied(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { PPM_RESOLUTION } from "./Constants.sol"; error AccessDenied(); error AlreadyExists(); error DoesNotExist(); error InvalidAddress(); error InvalidExternalAddress(); error InvalidFee(); error InvalidPool(); error InvalidPoolCollection(); error InvalidStakedBalance(); error InvalidToken(); error InvalidType(); error InvalidParam(); error NotEmpty(); error NotPayable(); error ZeroValue(); /** * @dev common utilities */ contract Utils { // allows execution by the caller only modifier only(address caller) { _only(caller); _; } function _only(address caller) internal view { if (msg.sender != caller) { revert AccessDenied(); } } // verifies that a value is greater than zero modifier greaterThanZero(uint256 value) { _greaterThanZero(value); _; } // error message binary size optimization function _greaterThanZero(uint256 value) internal pure { if (value == 0) { revert ZeroValue(); } } // validates an address - currently only checks that it isn't null modifier validAddress(address addr) { _validAddress(addr); _; } // error message binary size optimization function _validAddress(address addr) internal pure { if (addr == address(0)) { revert InvalidAddress(); } } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address addr) { _validExternalAddress(addr); _; } // error message binary size optimization function _validExternalAddress(address addr) internal view { if (addr == address(0) || addr == address(this)) { revert InvalidExternalAddress(); } } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { if (fee > PPM_RESOLUTION) { revert InvalidFee(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev Owned interface */ interface IOwned { /** * @dev returns the address of the current owner */ function owner() external view returns (address); /** * @dev allows transferring the contract ownership * * requirements: * * - the caller must be the owner of the contract * - the new owner still needs to accept the transfer */ function transferOwnership(address ownerCandidate) external; /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "./IVersioned.sol"; import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol"; /** * @dev this is the common interface for upgradeable contracts */ interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev an interface for a versioned contract */ interface IVersioned { function version() external view returns (uint16); }
returns a fraction with reduced components/
function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) { uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max); }
5,985,807
./full_match/44787/0x15a9F6335C5f7362FD2a7a2FF29294158e714C70/sources/src/Sway.sol
Function to mint tokens eventId EventId for the new token to The address that will receive the minted tokens. return A boolean that indicates if the operation was successful./
function mintToken(uint256 eventId, address to) public whenNotPaused onlyEventMinter(eventId) returns (bool) { lastId += 1; return _mintToken(eventId, lastId, to); }
13,245,819
contract Crowdsale { address[] public cold_wallets; uint public fundingGoal; uint public amountRaised; uint public deadline; mapping(address => uint256) public balanceOf; mapping(address => uint256) public fundingBalance; bool fundingGoalReached = false; bool crowdsaleClosed = false; event GoalReached(uint amountRaised); event FundTransfer(address backer, address beneficiary, uint amount); function Crowdsale( address[] coldWalletAddresses, uint fundingGoalInEthers, uint durationInMinutes ) { fundingGoal = fundingGoalInEthers * 1 ether; deadline = now + durationInMinutes * 1 minutes; /* we take a list of cold wallets in case of failure and */ for (uint i = 0; i < coldWalletAddresses.length; i ++) { cold_wallets.push(coldWalletAddresses[i]); fundingBalance[coldWalletAddresses[i]] = 0; } } /* The function without name is the default function that is called whenever anyone sends funds to a contract */ function () { if (crowdsaleClosed) throw; uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; /* fund the cold wallet with least funds */ address beneficiary = getBenificiary(); fundingBalance[beneficiary] += amount; if(!beneficiary.send(amount)) throw; if (amountRaised >= fundingGoal){ fundingGoalReached = true; GoalReached(amountRaised); crowdsaleClosed = true; } FundTransfer(msg.sender, beneficiary, amount); } modifier afterDeadline() { if (now >= deadline) _ } /* checks if the goal or time limit has been reached and ends the campaign */ function checkGoalReached() afterDeadline { if (amountRaised >= fundingGoal){ fundingGoalReached = true; GoalReached(amountRaised); } crowdsaleClosed = true; } /* definitely better ways of finding min. Can we indexOf an array? */ function getBenificiary() returns (address) { uint index; uint min = fundingBalance[cold_wallets[0]]; for (uint i = 1; i < cold_wallets.length; i ++) { uint balance = fundingBalance[cold_wallets[i]]; if(balance < min){ index = i; min = balance; } } return cold_wallets[index]; } }
The function without name is the default function that is called whenever anyone sends funds to a contract / fund the cold wallet with least funds /
function () { if (crowdsaleClosed) throw; uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; address beneficiary = getBenificiary(); fundingBalance[beneficiary] += amount; if(!beneficiary.send(amount)) throw; if (amountRaised >= fundingGoal){ fundingGoalReached = true; GoalReached(amountRaised); crowdsaleClosed = true; } FundTransfer(msg.sender, beneficiary, amount); }
12,731,793
./full_match/8453/0x7870837ffe670E62d4e601393D454f1b8649F7f9/sources/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20WrapperUpgradeable.sol
Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens./
function withdrawTo(address account, uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); SafeERC20Upgradeable.safeTransfer(underlying, account, amount); return true; }
11,543,955
./partial_match/1/0x28842B6E92a844DaEd9D3B8a3E85C2bB79bBC269/sources/DividendTracker.sol
Internal function that increases tokens to an account. Update magnifiedDividendCorrections to keep dividends unchanged. account The account that will receive the created tokens. value The amt that will be created.
function _increase(address account, uint256 value) internal { magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); }
3,542,360
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 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; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @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) public view returns (uint256) { return _balances[owner]; } /** * @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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } contract ExpandedIERC20 is IERC20 { // Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless. function burn(uint value) external; // Mints tokens and adds them to the balance of the `to` address. // Note: this method should be permissioned to only allow designated parties to mint tokens. function mint(address to, uint value) external; } // This interface allows derivative contracts to pay Oracle fees for their use of the system. interface StoreInterface { // Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH. function payOracleFees() external payable; // Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an // ERC20 token rather than ETH. All approved tokens are transfered. function payOracleFeesErc20(address erc20Address) external; // Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the // maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the // price feed in their favor. function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount); } interface ReturnCalculatorInterface { // Computes the return between oldPrice and newPrice. function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn); // Gets the effective leverage for the return calculator. // Note: if this parameter doesn't exist for this calculator, this method should return 1. function leverage() external view returns (int _leverage); } // This interface allows contracts to query unverified prices. interface PriceFeedInterface { // Whether this PriceFeeds provides prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have // been published for this identifier. function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price); // An event fired when a price is published. event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price); } contract AddressWhitelist is Ownable { enum Status { None, In, Out } mapping(address => Status) private whitelist; address[] private whitelistIndices; // Adds an address to the whitelist function addToWhitelist(address newElement) external onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddToWhitelist(newElement); } // Removes an address from the whitelist. function removeFromWhitelist(address elementToRemove) external onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemoveFromWhitelist(elementToRemove); } } // Checks whether an address is on the whitelist. function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; } // Gets all addresses that are currently included in the whitelist // Note: This method skips over, but still iterates through addresses. // It is possible for this call to run out of gas if a large number of // addresses have been removed. To prevent this unlikely scenario, we can // modify the implementation so that when addresses are removed, the last addresses // in the array is moved to the empty index. function getWhitelist() external view returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } event AddToWhitelist(address indexed addedAddress); event RemoveFromWhitelist(address indexed removedAddress); } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Registry is RegistryInterface, Withdrawable { using SafeMath for uint; // Array of all registeredDerivatives that are approved to use the UMA Oracle. RegisteredDerivative[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid, WasValid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; // Maps from derivative creator address to whether that derivative creator has been approved to register contracts. mapping(address => bool) private derivativeCreators; modifier onlyApprovedDerivativeCreator { require(derivativeCreators[msg.sender]); _; } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyApprovedDerivativeCreator { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender)); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit RegisterDerivative(derivativeAddress, partiesForEvent); } function addDerivativeCreator(address derivativeCreator) external onlyOwner { if (!derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = true; emit AddDerivativeCreator(derivativeCreator); } } function removeDerivativeCreator(address derivativeCreator) external onlyOwner { if (derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = false; emit RemoveDerivativeCreator(derivativeCreator); } } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { RegisteredDerivative storage derivative = registeredDerivatives[i]; if (derivativesToParties[derivative.derivativeAddress].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new RegisteredDerivative[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) { return registeredDerivatives; } function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) { return derivativeCreators[derivativeCreator]; } event RegisterDerivative(address indexed derivativeAddress, address[] parties); event AddDerivativeCreator(address indexed addedDerivativeCreator); event RemoveDerivativeCreator(address indexed removedDerivativeCreator); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract ContractCreator is Withdrawable { Registry internal registry; address internal oracleAddress; address internal storeAddress; address internal priceFeedAddress; constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress) public { registry = Registry(registryAddress); oracleAddress = _oracleAddress; storeAddress = _storeAddress; priceFeedAddress = _priceFeedAddress; } function _registerContract(address[] memory parties, address contractToRegister) internal { registry.registerDerivative(parties, contractToRegister); } } library TokenizedDerivativeParams { enum ReturnType { Linear, Compound } struct ConstructorParams { address sponsor; address admin; address oracle; address store; address priceFeed; uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying price that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of margin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18 ReturnType returnType; uint startingUnderlyingPrice; uint creationTime; } } // TokenizedDerivativeStorage: this library name is shortened due to it being used so often. library TDS { enum State { // The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as // it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state. // Possible state transitions: Disputed, Expired, Defaulted. Live, // Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in // time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn. // The resolution of these states moves the contract to the Settled state. Remargining is not allowed. // The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the // Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short // account. Otherwise, the dispute fee is added to the long margin account. // Possible state transitions: Settled. Disputed, // Contract expiration has been reached. // Possible state transitions: Settled. Expired, // The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and // move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to // Settled. // Possible state transitions: Settled. Defaulted, // UMA has manually triggered a shutdown of the account. // Possible state transitions: Settled. Emergency, // Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be // created, and contract can't remargin. // Possible state transitions: None. Settled } // The state of the token at a particular time. The state gets updated on remargin. struct TokenState { int underlyingPrice; int tokenPrice; uint time; } // The information in the following struct is only valid if in the midst of a Dispute. struct Dispute { int disputedNav; uint deposit; } struct WithdrawThrottle { uint startTime; uint remainingWithdrawal; } struct FixedParameters { // Fixed contract parameters. uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move that the long is protected against. uint disputeDeposit; // Percentage of margin requirement * 10^18 uint fixedFeePerSecond; // Percentage of nav*10^18 uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18 bytes32 product; TokenizedDerivativeParams.ReturnType returnType; uint initialTokenUnderlyingRatio; uint creationTime; string symbol; } struct ExternalAddresses { // Other addresses/contracts address sponsor; address admin; address apDelegate; OracleInterface oracle; StoreInterface store; PriceFeedInterface priceFeed; ReturnCalculatorInterface returnCalculator; IERC20 marginCurrency; } struct Storage { FixedParameters fixedParameters; ExternalAddresses externalAddresses; // Balances int shortBalance; int longBalance; State state; uint endTime; // The NAV of the contract always reflects the transition from (`prev`, `current`). // In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev` // and `latest` -> `current` (and then recompute). // In the case of a dispute, `current` might change (which is why we have to hold on to `prev`). TokenState referenceTokenState; TokenState currentTokenState; int nav; // Net asset value is measured in Wei Dispute disputeInfo; // Only populated once the contract enters a frozen state. int defaultPenaltyAmount; WithdrawThrottle withdrawThrottle; } } library TokenizedDerivativeUtils { using TokenizedDerivativeUtils for TDS.Storage; using SafeMath for uint; using SignedSafeMath for int; uint private constant SECONDS_PER_DAY = 86400; uint private constant SECONDS_PER_YEAR = 31536000; uint private constant INT_MAX = 2**255 - 1; uint private constant UINT_FP_SCALING_FACTOR = 10**18; int private constant INT_FP_SCALING_FACTOR = 10**18; modifier onlySponsor(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor); _; } modifier onlyAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrApDelegate(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); _; } // Contract initializer. Should only be called at construction. // Note: Must be a public function because structs cannot be passed as calldata (required data type for external // functions). function _initialize( TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public { s._setFixedParameters(params, symbol); s._setExternalAddresses(params); // Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally // creating rounding or overflow errors. require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9)); require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9)); // TODO(mrice32): we should have an ideal start time rather than blindly polling. (uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); // If nonzero, take the user input as the starting price. if (params.startingUnderlyingPrice != 0) { latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice); } require(latestUnderlyingPrice > 0); require(latestTime != 0); // Keep the ratio in case it's needed for margin computation. s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice)); require(s.fixedParameters.initialTokenUnderlyingRatio != 0); // Set end time to max value of uint to implement no expiry. if (params.expiry == 0) { s.endTime = ~uint(0); } else { require(params.expiry >= latestTime); s.endTime = params.expiry; } s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice); s.state = TDS.State.Live; } function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { s._remarginInternal(); int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (newTokenNav < 0) { newTokenNav = 0; } uint positiveTokenNav = _safeUintCast(newTokenNav); // Get any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). uint refund = s._pullSentMargin(marginForPurchase); // Subtract newTokenNav from amount sent. uint depositAmount = marginForPurchase.sub(positiveTokenNav); // Deposit additional margin into the short account. s._depositInternal(depositAmount); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. This should be 0 in this case, // but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure // the sender never loses money. refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav)); // Send the accumulated refund. s._sendMargin(refund); } function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external { require(s.state == TDS.State.Live || s.state == TDS.State.Settled); require(tokensToRedeem > 0); if (s.state == TDS.State.Live) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); s._remarginInternal(); require(s.state == TDS.State.Live); } ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); uint initialSupply = _totalSupply(); require(initialSupply > 0); _pullAuthorizedTokens(thisErc20Token, tokensToRedeem); thisErc20Token.burn(tokensToRedeem); emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem); // Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor // margin account. uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply); uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage); s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin)); assert(s.longBalance >= 0); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); s._sendMargin(tokenMargin); } function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) { require( s.state == TDS.State.Live, "Contract must be Live to dispute" ); uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit)); uint sendInconsistencyRefund = s._pullSentMargin(depositMargin); require(depositMargin >= requiredDeposit); uint overpaymentRefund = depositMargin.sub(requiredDeposit); s.state = TDS.State.Disputed; s.endTime = s.currentTokenState.time; s.disputeInfo.disputedNav = s.nav; s.disputeInfo.deposit = requiredDeposit; // Store the default penalty in case the dispute pushes the sponsor into default. s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav); s._requestOraclePrice(s.endTime); // Add the two types of refunds: // 1. The refund for ETH sent if it was > depositMargin. // 2. The refund for depositMargin > requiredDeposit. s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund)); } function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) { // Remargin before allowing a withdrawal, but only if in the live state. if (s.state == TDS.State.Live) { s._remarginInternal(); } // Make sure either in Live or Settled after any necessary remargin. require(s.state == TDS.State.Live || s.state == TDS.State.Settled); // If the contract has been settled or is in prefunded state then can // withdraw up to full balance. If the contract is in live state then // must leave at least the required margin. Not allowed to withdraw in // other states. int withdrawableAmount; if (s.state == TDS.State.Settled) { withdrawableAmount = s.shortBalance; } else { // Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit. uint currentTime = s.currentTokenState.time; if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) { // We've passed the previous s.withdrawThrottle window. Start new one. s.withdrawThrottle.startTime = currentTime; s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit); } int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState)); int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal); // Take the smallest of the two withdrawal limits. withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw; // Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above // ternary is more explicit. s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount); } // Can only withdraw the allowed amount. require( withdrawableAmount >= _safeIntCast(amount), "Attempting to withdraw more than allowed" ); // Transfer amount - Note: important to `-=` before the send so that the // function can not be called multiple times while waiting for transfer // to return. s.shortBalance = s.shortBalance.sub(_safeIntCast(amount)); emit Withdrawal(s.fixedParameters.symbol, amount); s._sendMargin(amount); } function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) { // Right now, only confirming prices in the defaulted state. require(s.state == TDS.State.Defaulted); // Remargin on agreed upon price. s._settleAgreedPrice(); } function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) { s.externalAddresses.apDelegate = _apDelegate; } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) { require(s.state == TDS.State.Live); s.state = TDS.State.Emergency; s.endTime = s.currentTokenState.time; s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime); s._requestOraclePrice(s.endTime); } function _settle(TDS.Storage storage s) external { s._settleInternal(); } function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { // Returns any refund due to sending more margin than the argument indicated (should only be able to happen in // the ETH case). uint refund = s._pullSentMargin(marginForPurchase); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase)); // Send the accumulated refund. s._sendMargin(refund); } function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) { // Only allow the s.externalAddresses.sponsor to deposit margin. uint refund = s._pullSentMargin(marginToDeposit); s._depositInternal(marginToDeposit); // Send any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). s._sendMargin(refund); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function _calcNAV(TDS.Storage storage s) external view returns (int navNew) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) { (TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance(); newTokenValue = newTokenState.tokenPrice; } // Returns the expected balance of the short margin account using the latest available Price Feed price. function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) { (, newShortMarginBalance) = s._calcNewTokenStateAndBalance(); } function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); // If the contract is in/will be moved to a settled state, the margin requirement will be 0. int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); } function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) { if (s.state == TDS.State.Settled) { // No margin needs to be maintained when the contract is settled. return 0; } return s._getRequiredMargin(s.currentTokenState); } function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) { TDS.State currentState = s.state; if (currentState == TDS.State.Settled) { return false; } // Technically we should also check if price will default the contract, but that isn't a normal flow of // operations that we want to simulate: we want to discourage the sponsor remargining into a default. (uint priceFeedTime, ) = s._getLatestPrice(); if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) { return false; } return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime); } function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); return (newTokenState.underlyingPrice, newTokenState.time); } function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance) { // TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted // so the logic can be written once and used twice. However, much of this was written post-audit, so it was // deemed preferable not to modify any state changing code that could potentially introduce new security // bugs. This should be done before the next contract audit. if (s.state == TDS.State.Settled) { // If the contract is Settled, just return the current contract state. return (s.currentTokenState, s.shortBalance); } // Grab the price feed pricetime. (uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice(); bool isContractLive = s.state == TDS.State.Live; bool isContractPostExpiry = priceFeedTime >= s.endTime; // If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values. if (isContractLive && priceFeedTime <= s.currentTokenState.time) { return (s.currentTokenState, s.shortBalance); } // Determine which previous price state to use when computing the new NAV. // If the contract is live, we use the reference for the linear return type or if the contract will immediately // move to expiry. bool shouldUseReferenceTokenState = isContractLive && (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry); TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState; // Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin. (uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ? (s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) : (priceFeedTime, priceFeedPrice); // Init the returned short balance to the current short balance. newShortMarginBalance = s.shortBalance; // Subtract the oracle fees from the short balance. newShortMarginBalance = isContractLive ? newShortMarginBalance.sub( _safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) : newShortMarginBalance; // Compute the new NAV newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime); int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance)); // If the contract is frozen or will move into expiry, we need to settle it, which means adding the default // penalty and dispute deposit if necessary. if (!isContractLive || isContractPostExpiry) { // Subtract default penalty (if necessary) from the short balance. bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState); if (inDefault) { int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty(); int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ? newShortMarginBalance : expectedDefaultPenalty; newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty); } // Add the dispute deposit to the short balance if necessary. if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) { int depositValue = _safeIntCast(s.disputeInfo.deposit); newShortMarginBalance = newShortMarginBalance.add(depositValue); } } } function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice) internal returns (int navNew) { int unitNav = _safeIntCast(startingTokenPrice); s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); // Starting NAV is always 0 in the TokenizedDerivative case. navNew = 0; } function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) { s._remarginInternal(); } function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) { if(address(s.externalAddresses.marginCurrency) == erc20Address) { uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this)); int totalBalances = s.shortBalance.add(s.longBalance); assert(totalBalances >= 0); uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit); require(withdrawableAmount >= amount); } IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal { // Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that // tokens fail to conform is that they do not return a bool from certain state-changing operations. This // contract was not designed to work with those tokens because of the additional complexity they would // introduce. s.externalAddresses.marginCurrency = IERC20(params.marginCurrency); s.externalAddresses.oracle = OracleInterface(params.oracle); s.externalAddresses.store = StoreInterface(params.store); s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed); s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator); // Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product. require(s.externalAddresses.oracle.isIdentifierSupported(params.product)); require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product)); s.externalAddresses.sponsor = params.sponsor; s.externalAddresses.admin = params.admin; } function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal { // Ensure only valid enum values are provided. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.returnType == TokenizedDerivativeParams.ReturnType.Linear); // Fee must be 0 if the returnType is linear. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0); // The default penalty must be less than the required margin. require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR); s.fixedParameters.returnType = params.returnType; s.fixedParameters.defaultPenalty = params.defaultPenalty; s.fixedParameters.product = params.product; s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR); s.fixedParameters.disputeDeposit = params.disputeDeposit; s.fixedParameters.supportedMove = params.supportedMove; s.fixedParameters.withdrawLimit = params.withdrawLimit; s.fixedParameters.creationTime = params.creationTime; s.fixedParameters.symbol = symbol; } // _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for // _remargin(). function _remarginInternal(TDS.Storage storage s) internal { // If the state is not live, remargining does not make sense. require(s.state == TDS.State.Live); (uint latestTime, int latestPrice) = s._getLatestPrice(); // Checks whether contract has ended. if (latestTime <= s.currentTokenState.time) { // If the price feed hasn't advanced, remargining should be a no-op. return; } // Save the penalty using the current state in case it needs to be used. int potentialPenaltyAmount = s._computeDefaultPenalty(); if (latestTime >= s.endTime) { s.state = TDS.State.Expired; emit Expired(s.fixedParameters.symbol, s.endTime); // Applies the same update a second time to effectively move the current state to the reference state. int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time); assert(recomputedNav == s.nav); uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime); // Save the precomputed default penalty in case the expiry price pushes the sponsor into default. s.defaultPenaltyAmount = potentialPenaltyAmount; // We have no idea what the price was, exactly at s.endTime, so we can't set // s.currentTokenState, or update the nav, or do anything. s._requestOraclePrice(s.endTime); s._payOracleFees(feeAmount); return; } uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime); // Update nav of contract. int navNew = s._computeNav(latestPrice, latestTime); // Update the balances of the contract. s._updateBalances(navNew); // Make sure contract has not moved into default. bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { s.state = TDS.State.Defaulted; s.defaultPenaltyAmount = potentialPenaltyAmount; s.endTime = latestTime; // Change end time to moment when default occurred. emit Default(s.fixedParameters.symbol, latestTime, s.nav); s._requestOraclePrice(latestTime); } s._payOracleFees(feeAmount); } function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) { s._remarginInternal(); // Verify that remargining didn't push the contract into expiry or default. require(s.state == TDS.State.Live); int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (purchasedNav < 0) { purchasedNav = 0; } // Ensures that requiredNav >= navSent. refund = navSent.sub(_safeUintCast(purchasedNav)); s.longBalance = s.longBalance.add(purchasedNav); ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); thisErc20Token.mint(msg.sender, tokensToPurchase); emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); // Make sure this still satisfies the margin requirement. require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState)); } function _depositInternal(TDS.Storage storage s, uint value) internal { // Make sure that we are in a "depositable" state. require(s.state == TDS.State.Live); s.shortBalance = s.shortBalance.add(_safeIntCast(value)); emit Deposited(s.fixedParameters.symbol, value); } function _settleInternal(TDS.Storage storage s) internal { TDS.State startingState = s.state; require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired || startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency); s._settleVerifiedPrice(); if (startingState == TDS.State.Disputed) { int depositValue = _safeIntCast(s.disputeInfo.deposit); if (s.nav != s.disputeInfo.disputedNav) { s.shortBalance = s.shortBalance.add(depositValue); } else { s.longBalance = s.longBalance.add(depositValue); } } } // Deducts the fees from the margin account. function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) { feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime); s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount)); // If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the // contract. } // Pays out the fees to the Oracle. function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); } else { require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } } function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal view returns (uint feeAmount) { // The profit from corruption is set as the max(longBalance, shortBalance). int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance; uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc)); // Ensure the fee returned can actually be paid by the short margin account. uint shortBalance = _safeUintCast(s.shortBalance); return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount; } function _computeNewTokenState(TDS.Storage storage s, TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime) internal view returns (TDS.TokenState memory newTokenState) { int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn( beginningTokenState.underlyingPrice, latestUnderlyingPrice); int tokenReturn = underlyingReturn.sub( _safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time)))); int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR); // In the compound case, don't allow the token price to go below 0. if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) { tokenMultiplier = 0; } int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier); newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime); } function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState) internal view returns (bool doesSatisfyRequirement) { return s._getRequiredMargin(tokenState) <= balance; } function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal { uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime); if (expectedTime == 0) { // The Oracle price is already available, settle the contract right away. s._settleInternal(); } } function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) { (latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); require(latestTime != 0); } function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) { navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime); } else { assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear); navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime); } } function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { s.referenceTokenState = s.currentTokenState; s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { // Only update the time - don't update the prices becuase all price changes are relative to the initial price. s.referenceTokenState.time = s.currentTokenState.time; s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) { // We're updating `last` based on what the Oracle has told us. assert(s.endTime == recomputeTime); s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } // Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all // of the settlement logic including assessing penalties and then moves the state to `Settled`. function _settleWithPrice(TDS.Storage storage s, int price) internal { // Remargin at whatever price we're using (verified or unverified). s._updateBalances(s._recomputeNav(price, s.endTime)); bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { int expectedDefaultPenalty = s._getDefaultPenalty(); int penalty = (s.shortBalance < expectedDefaultPenalty) ? s.shortBalance : expectedDefaultPenalty; s.shortBalance = s.shortBalance.sub(penalty); s.longBalance = s.longBalance.add(penalty); } s.state = TDS.State.Settled; emit Settled(s.fixedParameters.symbol, s.endTime, s.nav); } function _updateBalances(TDS.Storage storage s, int navNew) internal { // Compute difference -- Add the difference to owner and subtract // from counterparty. Then update nav state variable. int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance); s.nav = navNew; s.longBalance = s.longBalance.add(longDiff); s.shortBalance = s.shortBalance.sub(longDiff); } function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return s.defaultPenaltyAmount; } function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty); } function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState) internal view returns (int requiredMargin) { int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage()); int effectiveNotional; if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) { int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude); effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR); } else { int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply()); effectiveNotional = currentNav.mul(leverageMagnitude); } // Take the absolute value of the notional since a negative notional has similar risk properties to a positive // notional of the same size, and, therefore, requires the same margin. requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove); } function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) { if (address(s.externalAddresses.marginCurrency) == address(0x0)) { // Refund is any amount of ETH that was sent that was above the amount that was expected. // Note: SafeMath will force a revert if msg.value < expectedMargin. return msg.value.sub(expectedMargin); } else { // If we expect an ERC20 token, no ETH should be sent. require(msg.value == 0); _pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin); // There is never a refund in the ERC20 case since we use the argument to determine how much to "pull". return 0; } } function _sendMargin(TDS.Storage storage s, uint amount) internal { // There's no point in attempting a send if there's nothing to send. if (amount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { msg.sender.transfer(amount); } else { require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount)); } } function _settleAgreedPrice(TDS.Storage storage s) internal { int agreedPrice = s.currentTokenState.underlyingPrice; s._settleWithPrice(agreedPrice); } function _settleVerifiedPrice(TDS.Storage storage s) internal { int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime); s._settleWithPrice(oraclePrice); } function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private { // If nothing is being pulled, there's no point in calling a transfer. if (amountToPull > 0) { require(erc20.transferFrom(msg.sender, address(this), amountToPull)); } } // Gets the change in balance for the long side. // Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; // Long balance cannot go below zero. if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); // Cannot pull more margin from the short than is available. if (longDiff > shortBalance) { longDiff = shortBalance; } } function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) { int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice); navNew = navPreDivision.div(INT_FP_SCALING_FACTOR); // The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens // cannot be purchased or backed with less than their true value. if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) { navNew = navNew.add(1); } } function _totalSupply() private view returns (uint totalSupply) { ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); return thisErc20Token.totalSupply(); } function _takePercentage(uint value, uint percentage) private pure returns (uint result) { return value.mul(percentage).div(UINT_FP_SCALING_FACTOR); } function _takePercentage(int value, uint percentage) private pure returns (int result) { return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR); } function _takePercentage(int value, int percentage) private pure returns (int result) { return value.mul(percentage).div(INT_FP_SCALING_FACTOR); } function _absoluteValue(int value) private pure returns (int result) { return value < 0 ? value.mul(-1) : value; } function _safeIntCast(uint value) private pure returns (int result) { require(value <= INT_MAX); return int(value); } function _safeUintCast(int value) private pure returns (uint result) { require(value >= 0); return uint(value); } // Note that we can't have the symbol parameter be `indexed` due to: // TypeError: Indexed reference types cannot yet be used with ABIEncoderV2. // An event emitted when the NAV of the contract changes. event NavUpdated(string symbol, int newNav, int newTokenPrice); // An event emitted when the contract enters the Default state on a remargin. event Default(string symbol, uint defaultTime, int defaultNav); // An event emitted when the contract settles. event Settled(string symbol, uint settleTime, int finalNav); // An event emitted when the contract expires. event Expired(string symbol, uint expiryTime); // An event emitted when the contract's NAV is disputed by the sponsor. event Disputed(string symbol, uint timeDisputed, int navDisputed); // An event emitted when the contract enters emergency shutdown. event EmergencyShutdownTransition(string symbol, uint shutdownTime); // An event emitted when tokens are created. event TokensCreated(string symbol, uint numTokensCreated); // An event emitted when tokens are redeemed. event TokensRedeemed(string symbol, uint numTokensRedeemed); // An event emitted when margin currency is deposited. event Deposited(string symbol, uint amount); // An event emitted when margin currency is withdrawn. event Withdrawal(string symbol, uint amount); } // TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality. contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 { using TokenizedDerivativeUtils for TDS.Storage; // Note: these variables are to give ERC20 consumers information about the token. string public name; string public symbol; uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase TDS.Storage public derivativeStorage; constructor( TokenizedDerivativeParams.ConstructorParams memory params, string memory _name, string memory _symbol ) public { // Set token properties. name = _name; symbol = _symbol; // Initialize the contract. derivativeStorage._initialize(params, _symbol); } // Creates tokens with sent margin and returns additional margin. function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._createTokens(marginForPurchase, tokensToPurchase); } // Creates tokens with sent margin and deposits additional margin in short account. function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase); } // Redeems tokens for margin currency. function redeemTokens(uint tokensToRedeem) external { derivativeStorage._redeemTokens(tokensToRedeem); } // Triggers a price dispute for the most recent remargin time. function dispute(uint depositMargin) external payable { derivativeStorage._dispute(depositMargin); } // Withdraws `amount` from short margin account. function withdraw(uint amount) external { derivativeStorage._withdraw(amount); } // Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and // short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements. function remargin() external { derivativeStorage._remargin(); } // Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on // contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long // account. function acceptPriceAndSettle() external { derivativeStorage._acceptPriceAndSettle(); } // Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no // Delegate AP. function setApDelegate(address apDelegate) external { derivativeStorage._setApDelegate(apDelegate); } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function emergencyShutdown() external { derivativeStorage._emergencyShutdown(); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function calcNAV() external view returns (int navNew) { return derivativeStorage._calcNAV(); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function calcTokenValue() external view returns (int newTokenValue) { return derivativeStorage._calcTokenValue(); } // Returns the expected balance of the short margin account using the latest available Price Feed price. function calcShortMarginBalance() external view returns (int newShortMarginBalance) { return derivativeStorage._calcShortMarginBalance(); } // Returns the expected short margin in excess of the margin requirement using the latest available Price Feed // price. Value will be negative if the short margin is expected to be below the margin requirement. function calcExcessMargin() external view returns (int excessMargin) { return derivativeStorage._calcExcessMargin(); } // Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the // latest available Price Feed price. function getCurrentRequiredMargin() external view returns (int requiredMargin) { return derivativeStorage._getCurrentRequiredMargin(); } // Returns whether the contract can be settled, i.e., is it valid to call settle() now. function canBeSettled() external view returns (bool canContractBeSettled) { return derivativeStorage._canBeSettled(); } // Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if // the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. // Reverts if no Oracle price is available but an Oracle price is required. function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); } // When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract // into the `Settled` state. function settle() external { derivativeStorage._settle(); } // Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call) // to the short account. function deposit(uint amountToDeposit) external payable { derivativeStorage._deposit(amountToDeposit); } // Allows the sponsor to withdraw any ERC20 balance that is not the margin token. function withdrawUnexpectedErc20(address erc20Address, uint amount) external { derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount); } // ExpandedIERC20 methods. modifier onlyThis { require(msg.sender == address(this)); _; } // Only allow calls from this contract or its libraries to burn tokens. function burn(uint value) external onlyThis { // Only allow calls from this contract or its libraries to burn tokens. _burn(msg.sender, value); } // Only allow calls from this contract or its libraries to mint tokens. function mint(address to, uint256 value) external onlyThis { _mint(to, value); } // These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events // here as well. event NavUpdated(string symbol, int newNav, int newTokenPrice); event Default(string symbol, uint defaultTime, int defaultNav); event Settled(string symbol, uint settleTime, int finalNav); event Expired(string symbol, uint expiryTime); event Disputed(string symbol, uint timeDisputed, int navDisputed); event EmergencyShutdownTransition(string symbol, uint shutdownTime); event TokensCreated(string symbol, uint numTokensCreated); event TokensRedeemed(string symbol, uint numTokensRedeemed); event Deposited(string symbol, uint amount); event Withdrawal(string symbol, uint amount); } contract TokenizedDerivativeCreator is ContractCreator, Testable { struct Params { uint defaultPenalty; // Percentage of mergin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of mergin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of shortBalance * 10^18 TokenizedDerivativeParams.ReturnType returnType; uint startingUnderlyingPrice; string name; string symbol; } AddressWhitelist public sponsorWhitelist; AddressWhitelist public returnCalculatorWhitelist; AddressWhitelist public marginCurrencyWhitelist; constructor( address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress, address _sponsorWhitelist, address _returnCalculatorWhitelist, address _marginCurrencyWhitelist, bool _isTest ) public ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress) Testable(_isTest) { sponsorWhitelist = AddressWhitelist(_sponsorWhitelist); returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist); marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist); } function createTokenizedDerivative(Params memory params) public returns (address derivativeAddress) { TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol); address[] memory parties = new address[](1); parties[0] = msg.sender; _registerContract(parties, address(derivative)); return address(derivative); } // Converts createTokenizedDerivative params to TokenizedDerivative constructor params. function _convertParams(Params memory params) private view returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams) { // Copy and verify externally provided variables. require(sponsorWhitelist.isOnWhitelist(msg.sender)); constructorParams.sponsor = msg.sender; require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator)); constructorParams.returnCalculator = params.returnCalculator; require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency)); constructorParams.marginCurrency = params.marginCurrency; constructorParams.defaultPenalty = params.defaultPenalty; constructorParams.supportedMove = params.supportedMove; constructorParams.product = params.product; constructorParams.fixedYearlyFee = params.fixedYearlyFee; constructorParams.disputeDeposit = params.disputeDeposit; constructorParams.startingTokenPrice = params.startingTokenPrice; constructorParams.expiry = params.expiry; constructorParams.withdrawLimit = params.withdrawLimit; constructorParams.returnType = params.returnType; constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice; // Copy internal variables. constructorParams.priceFeed = priceFeedAddress; constructorParams.oracle = oracleAddress; constructorParams.store = storeAddress; constructorParams.admin = oracleAddress; constructorParams.creationTime = getCurrentTime(); } }
Pays out the fees to the Oracle.
function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } }
972,348
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // constants import "./constants.sol"; // interfaces import "./interfaces/IERC725Y.sol"; // modules import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import "./utils/OwnableUnset.sol"; /** * @title Core implementation of ERC725 Y General key/value store * @author Fabian Vogelsteller <[email protected]> * @dev Contract module which provides the ability to set arbitrary key value sets that can be changed over time * It is intended to standardise certain keys value pairs to allow automated retrievals and interactions * from interfaces and other smart contracts */ abstract contract ERC725YCore is OwnableUnset, ERC165Storage, IERC725Y { /** * @dev Map the keys to their values */ mapping(bytes32 => bytes) internal store; /* Public functions */ /** * @inheritdoc IERC725Y */ function getData(bytes32[] memory keys) public view virtual override returns (bytes[] memory values) { values = new bytes[](keys.length); for (uint256 i = 0; i < keys.length; i++) { values[i] = _getData(keys[i]); } return values; } /** * @inheritdoc IERC725Y */ function setData(bytes32[] memory _keys, bytes[] memory _values) public virtual override onlyOwner { require(_keys.length == _values.length, "Keys length not equal to values length"); for (uint256 i = 0; i < _keys.length; i++) { _setData(_keys[i], _values[i]); } } /* Internal functions */ /** * @notice Gets singular data at a given `key` * @param key The key which value to retrieve * @return value The data stored at the key */ function _getData(bytes32 key) internal view virtual returns (bytes memory value) { return store[key]; } /** * @notice Sets singular data at a given `key` * @param key The key which value to retrieve * @param value The value to set */ function _setData(bytes32 key, bytes memory value) internal virtual { store[key] = value; emit DataChanged(key, value); } }
Sets singular data at a given `key` key The key which value to retrieve value The value to set/
function _setData(bytes32 key, bytes memory value) internal virtual { store[key] = value; emit DataChanged(key, value); }
6,440,263
./partial_match/42161/0x6852024A3051DE1513129CeD4DdB74B3454bef30/sources/contracts/CamelotPair.sol
force reserves to match balances
function sync() external lock { uint token0Balance = IERC20(token0).balanceOf(address(this)); uint token1Balance = IERC20(token1).balanceOf(address(this)); require(token0Balance != 0 && token1Balance != 0, "CamelotPair: liquidity ratio not initialized"); _update(token0Balance, token1Balance); }
3,493,240
./full_match/1/0x8EEdEFe828A0f16C8fc80e46a87Bc0f1De2d960c/sources/contracts/DGMV.sol
Function to increase the allowance of another account/
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; }
4,864,137
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; pragma solidity ^0.8.0; interface IWhales { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } contract Ocean is IERC721ReceiverUpgradeable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { event TokenStaked(address owner, uint128 tokenId); event WhalesMinted(address owner, uint256 amount); event TokenUnStaked(address owner, uint128 tokenId); // base reward rate uint256 DAILY_WHALES_BASE_RATE; uint256 DAILY_WHALES_RATE_TIER_1; uint256 DAILY_WHALES_RATE_TIER_2; uint256 DAILY_WHALES_RATE_TIER_3; uint256 DAILY_WHALES_RATE_TIER_4; uint256 DAILY_WHALES_RATE_TIER_5; uint256 DAILY_WHALES_RATE_LEGENDRY; uint256 INITIAL_MINT_REWARD_TIER_1; uint256 INITIAL_MINT_REWARD_TIER_2; uint256 INITIAL_MINT_REWARD_TIER_3; uint256 INITIAL_MINT_REWARD_TIER_4; uint256 INITIAL_MINT_REWARD_LEGENDRY_TIER; // amount of $WHALES earned so far // number of Blues in the ocean uint128 public totalBluesStaked; // the last time $WHALES was claimed //uint16 public lastInteractionTimeStamp; // max $WHALES supply IERC721 Blues; IWhales Whales; mapping(address => uint256) public totalWhalesEarnedPerAddress; mapping(address => uint256) public lastInteractionTimeStamp; mapping(address => uint256) public userMultiplier; mapping(address => uint16) public totalBluesStakedPerAddress; mapping(address => bool) public userFirstInteracted; mapping(uint256 => bool) public initialMintClaimLedger; mapping(address => uint8) public legendryHoldingsPerUser; address[5600] public ocean; function initialize(address _whales, address _blues) external initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); Blues = IERC721(_blues); Whales = IWhales(_whales); DAILY_WHALES_BASE_RATE = 10 ether; DAILY_WHALES_RATE_TIER_1 = 11 ether; DAILY_WHALES_RATE_TIER_2 = 12 ether; DAILY_WHALES_RATE_TIER_3 = 13 ether; DAILY_WHALES_RATE_TIER_4 = 14 ether; DAILY_WHALES_RATE_TIER_5 = 15 ether; DAILY_WHALES_RATE_LEGENDRY = 50 ether; INITIAL_MINT_REWARD_LEGENDRY_TIER = 100 ether; INITIAL_MINT_REWARD_TIER_1 = 50 ether; INITIAL_MINT_REWARD_TIER_2 = 20 ether; INITIAL_MINT_REWARD_TIER_3 = 10 ether; } // entry point and main staking function. // takes an array of tokenIDs, and checks if the caller is // the owner of each token. // It then transfers the token to the Ocean contract. // At the end, it sets the userFirstInteracted mapping to true. // This is to prevent rewards calculation BEFORE having anything staked. // Otherwise, it leads to massive rewards. // The lastInteractionTimeStamp mapping is also updated. function addManyBluesToOcean(uint16[] calldata tokenIds) external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; require(tokenIds.length >= 1, "need at least 1 blue"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], true); totalBluesStakedPerAddress[msg.sender]++; _addBlueToOcean(msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); // only runs one time, the first time the user calls this function. if (userFirstInteracted[msg.sender] == false) { lastInteractionTimeStamp[msg.sender] = block.timestamp; userFirstInteracted[msg.sender] = true; } } // internal utility function that transfers the token and emits an event. function _addBlueToOcean(address account, uint16 tokenId) internal whenNotPaused { ocean[tokenId] = account; Blues.safeTransferFrom(msg.sender, address(this), tokenId); emit TokenStaked(msg.sender, tokenId); } // This function recalculate the user's holders multiplier // whenever they stake or unstake. // There are a total of 5 yeild tiers..depending on the number of tokens staked. function _adjustUserDailyWhalesMultiplier(uint256 stakedBlues) internal { if (stakedBlues < 5) userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; else { if (stakedBlues >= 5 && stakedBlues <= 9) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_1; else if (stakedBlues >= 10 && stakedBlues <= 19) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_2; else if (stakedBlues >= 20 && stakedBlues <= 39) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_3; else if (stakedBlues >= 40 && stakedBlues <= 79) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_4; else userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_5; } } function _adjustUserLegendryWhalesMultiplier(uint256 tokenId, bool staking) internal { //todo add support for the other 1/1 for the public mint if (staking) { if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]++; } else { if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]--; } } // claims the rewards owed till now and updates the lastInteractionTimeStamp mapping. // also emits an event, etc.. // finally, it sets the totalWhalesEarnedPerAddress to 0. function claimWhalesWithoutUnstaking() external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); require( totalWhalesEarnedPerAddress[msg.sender] > 0, "No whales to claim" ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } // same as the previous function, except this one unstakes as well. // it verfied the owner in the Stake struct to be the msg.sender // it also verifies the the current owner is this contract. // it then decrease the total number staked for the user // and then calls safeTransferFrom. // it then mints the tokens. // finally, it calls _adjustUserDailyWhalesMultiplier function claimWhalesAndUnstake(uint256[] calldata tokenIds) public nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == address(this), "This Blue is not staked" ); require( ocean[tokenIds[i]] == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], false); delete ocean[tokenIds[i]]; totalBluesStakedPerAddress[msg.sender]--; Blues.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } // Each minting tier is elligble for a token claim based on how early they minted. // first 500 tokenIds get 50 whales for instance. // there are 3 tiers. function claimInitialMintingRewards(uint256[] calldata tokenIds) public nonReentrant whenNotPaused { uint256 rewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this token" ); require( initialMintClaimLedger[tokenIds[i]] == false, "Rewards already claimed for this token" ); initialMintClaimLedger[tokenIds[i]] = true; if (tokenIds[i] <= 500) rewards += INITIAL_MINT_REWARD_TIER_1; else if (tokenIds[i] > 500 && tokenIds[i] < 1500) rewards += INITIAL_MINT_REWARD_TIER_2; else if (tokenIds[i] > 5555 || isLegendary(i)) rewards += INITIAL_MINT_REWARD_LEGENDRY_TIER; else rewards += INITIAL_MINT_REWARD_TIER_3; } Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); } function isLegendary(uint256 tokenID) public pure returns (bool) { if ( tokenID == 756 || tokenID == 2133 || tokenID == 1111 || tokenID == 999 || tokenID == 888 || tokenID == 435 || tokenID == 891 || tokenID == 918 || tokenID == 123 || tokenID == 432 || tokenID == 543 || tokenID == 444 || tokenID == 333 || tokenID == 222 || tokenID == 235 || tokenID == 645 || tokenID == 898 || tokenID == 1190 || tokenID == 3082 || tokenID == 3453 || tokenID == 2876 || tokenID == 5200 || tokenID == 451 ) return true; return false; } // The main accounting modifier. // It runs when the user interacts with any other function. // and before the function itself. // stores the owed results till now in the totalWhalesEarnedPerAddress // mapping. It then sets the lastInteractionTimeStamp to the current block.timestamp modifier updateRewardsForUser(address account) { if (userFirstInteracted[msg.sender]) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * totalBluesStakedPerAddress[msg.sender] * userMultiplier[msg.sender]) / 1 days; // now accounting if they are holding legendries. if (legendryHoldingsPerUser[msg.sender] > 0) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * (legendryHoldingsPerUser[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) / 1 days; } lastInteractionTimeStamp[msg.sender] = block.timestamp; } _; } //read only function. function getDailyYield(address account) external view returns (uint256) { uint256 yeild = (totalBluesStakedPerAddress[account] * userMultiplier[account]); yeild += (legendryHoldingsPerUser[account] * DAILY_WHALES_RATE_LEGENDRY); return yeild; } function getOcean() external view returns (address[5600] memory) { return ocean; } function setBlues(address _blues) external onlyOwner { Blues = IERC721(_blues); } function setWhales(address _whales) external onlyOwner { Whales = IWhales(_whales); } // only owner function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { return this.onERC721Received.selector; } } // 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 (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 { __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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @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. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ 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 (last updated v4.5.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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // 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; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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); _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"); _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 {} } // 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 proxied contracts do not make use of 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 (last updated v4.5.0) (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 * ==== * * [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 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/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 (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 (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 (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); }
base reward rate amount of $WHALES earned so far number of Blues in the ocean the last time $WHALES was claimeduint16 public lastInteractionTimeStamp; max $WHALES supply
{ event TokenStaked(address owner, uint128 tokenId); event WhalesMinted(address owner, uint256 amount); event TokenUnStaked(address owner, uint128 tokenId); uint256 DAILY_WHALES_BASE_RATE; uint256 DAILY_WHALES_RATE_TIER_1; uint256 DAILY_WHALES_RATE_TIER_2; uint256 DAILY_WHALES_RATE_TIER_3; uint256 DAILY_WHALES_RATE_TIER_4; uint256 DAILY_WHALES_RATE_TIER_5; uint256 DAILY_WHALES_RATE_LEGENDRY; uint256 INITIAL_MINT_REWARD_TIER_1; uint256 INITIAL_MINT_REWARD_TIER_2; uint256 INITIAL_MINT_REWARD_TIER_3; uint256 INITIAL_MINT_REWARD_TIER_4; uint256 INITIAL_MINT_REWARD_LEGENDRY_TIER; uint128 public totalBluesStaked; IERC721 Blues; IWhales Whales; mapping(address => uint256) public totalWhalesEarnedPerAddress; mapping(address => uint256) public lastInteractionTimeStamp; mapping(address => uint256) public userMultiplier; mapping(address => uint16) public totalBluesStakedPerAddress; mapping(address => bool) public userFirstInteracted; mapping(uint256 => bool) public initialMintClaimLedger; mapping(address => uint8) public legendryHoldingsPerUser; address[5600] public ocean; function initialize(address _whales, address _blues) external initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); Blues = IERC721(_blues); Whales = IWhales(_whales); DAILY_WHALES_BASE_RATE = 10 ether; DAILY_WHALES_RATE_TIER_1 = 11 ether; DAILY_WHALES_RATE_TIER_2 = 12 ether; DAILY_WHALES_RATE_TIER_3 = 13 ether; DAILY_WHALES_RATE_TIER_4 = 14 ether; DAILY_WHALES_RATE_TIER_5 = 15 ether; DAILY_WHALES_RATE_LEGENDRY = 50 ether; INITIAL_MINT_REWARD_LEGENDRY_TIER = 100 ether; INITIAL_MINT_REWARD_TIER_1 = 50 ether; INITIAL_MINT_REWARD_TIER_2 = 20 ether; INITIAL_MINT_REWARD_TIER_3 = 10 ether; } function addManyBluesToOcean(uint16[] calldata tokenIds) external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; require(tokenIds.length >= 1, "need at least 1 blue"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], true); totalBluesStakedPerAddress[msg.sender]++; _addBlueToOcean(msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); if (userFirstInteracted[msg.sender] == false) { lastInteractionTimeStamp[msg.sender] = block.timestamp; userFirstInteracted[msg.sender] = true; } } function addManyBluesToOcean(uint16[] calldata tokenIds) external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; require(tokenIds.length >= 1, "need at least 1 blue"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], true); totalBluesStakedPerAddress[msg.sender]++; _addBlueToOcean(msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); if (userFirstInteracted[msg.sender] == false) { lastInteractionTimeStamp[msg.sender] = block.timestamp; userFirstInteracted[msg.sender] = true; } } function addManyBluesToOcean(uint16[] calldata tokenIds) external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; require(tokenIds.length >= 1, "need at least 1 blue"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], true); totalBluesStakedPerAddress[msg.sender]++; _addBlueToOcean(msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); if (userFirstInteracted[msg.sender] == false) { lastInteractionTimeStamp[msg.sender] = block.timestamp; userFirstInteracted[msg.sender] = true; } } function _addBlueToOcean(address account, uint16 tokenId) internal whenNotPaused { ocean[tokenId] = account; Blues.safeTransferFrom(msg.sender, address(this), tokenId); emit TokenStaked(msg.sender, tokenId); } function _adjustUserDailyWhalesMultiplier(uint256 stakedBlues) internal { if (stakedBlues < 5) userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; else { if (stakedBlues >= 5 && stakedBlues <= 9) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_1; else if (stakedBlues >= 10 && stakedBlues <= 19) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_2; else if (stakedBlues >= 20 && stakedBlues <= 39) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_3; else if (stakedBlues >= 40 && stakedBlues <= 79) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_4; else userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_5; } } function _adjustUserDailyWhalesMultiplier(uint256 stakedBlues) internal { if (stakedBlues < 5) userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; else { if (stakedBlues >= 5 && stakedBlues <= 9) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_1; else if (stakedBlues >= 10 && stakedBlues <= 19) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_2; else if (stakedBlues >= 20 && stakedBlues <= 39) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_3; else if (stakedBlues >= 40 && stakedBlues <= 79) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_4; else userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_5; } } function _adjustUserLegendryWhalesMultiplier(uint256 tokenId, bool staking) internal { if (staking) { if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]++; if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]--; } } function _adjustUserLegendryWhalesMultiplier(uint256 tokenId, bool staking) internal { if (staking) { if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]++; if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]--; } } } else { function claimWhalesWithoutUnstaking() external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); require( totalWhalesEarnedPerAddress[msg.sender] > 0, "No whales to claim" ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } function claimWhalesAndUnstake(uint256[] calldata tokenIds) public nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == address(this), "This Blue is not staked" ); require( ocean[tokenIds[i]] == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], false); delete ocean[tokenIds[i]]; totalBluesStakedPerAddress[msg.sender]--; Blues.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } function claimWhalesAndUnstake(uint256[] calldata tokenIds) public nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == address(this), "This Blue is not staked" ); require( ocean[tokenIds[i]] == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], false); delete ocean[tokenIds[i]]; totalBluesStakedPerAddress[msg.sender]--; Blues.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } function claimInitialMintingRewards(uint256[] calldata tokenIds) public nonReentrant whenNotPaused { uint256 rewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this token" ); require( initialMintClaimLedger[tokenIds[i]] == false, "Rewards already claimed for this token" ); initialMintClaimLedger[tokenIds[i]] = true; if (tokenIds[i] <= 500) rewards += INITIAL_MINT_REWARD_TIER_1; else if (tokenIds[i] > 500 && tokenIds[i] < 1500) rewards += INITIAL_MINT_REWARD_TIER_2; else if (tokenIds[i] > 5555 || isLegendary(i)) rewards += INITIAL_MINT_REWARD_LEGENDRY_TIER; else rewards += INITIAL_MINT_REWARD_TIER_3; } Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); } function claimInitialMintingRewards(uint256[] calldata tokenIds) public nonReentrant whenNotPaused { uint256 rewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this token" ); require( initialMintClaimLedger[tokenIds[i]] == false, "Rewards already claimed for this token" ); initialMintClaimLedger[tokenIds[i]] = true; if (tokenIds[i] <= 500) rewards += INITIAL_MINT_REWARD_TIER_1; else if (tokenIds[i] > 500 && tokenIds[i] < 1500) rewards += INITIAL_MINT_REWARD_TIER_2; else if (tokenIds[i] > 5555 || isLegendary(i)) rewards += INITIAL_MINT_REWARD_LEGENDRY_TIER; else rewards += INITIAL_MINT_REWARD_TIER_3; } Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); } function isLegendary(uint256 tokenID) public pure returns (bool) { if ( tokenID == 756 || tokenID == 2133 || tokenID == 1111 || tokenID == 999 || tokenID == 888 || tokenID == 435 || tokenID == 891 || tokenID == 918 || tokenID == 123 || tokenID == 432 || tokenID == 543 || tokenID == 444 || tokenID == 333 || tokenID == 222 || tokenID == 235 || tokenID == 645 || tokenID == 898 || tokenID == 1190 || tokenID == 3082 || tokenID == 3453 || tokenID == 2876 || tokenID == 5200 || tokenID == 451 ) return true; return false; } modifier updateRewardsForUser(address account) { if (userFirstInteracted[msg.sender]) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * totalBluesStakedPerAddress[msg.sender] * userMultiplier[msg.sender]) / 1 days; if (legendryHoldingsPerUser[msg.sender] > 0) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * (legendryHoldingsPerUser[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) / 1 days; } lastInteractionTimeStamp[msg.sender] = block.timestamp; } _; } modifier updateRewardsForUser(address account) { if (userFirstInteracted[msg.sender]) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * totalBluesStakedPerAddress[msg.sender] * userMultiplier[msg.sender]) / 1 days; if (legendryHoldingsPerUser[msg.sender] > 0) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * (legendryHoldingsPerUser[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) / 1 days; } lastInteractionTimeStamp[msg.sender] = block.timestamp; } _; } modifier updateRewardsForUser(address account) { if (userFirstInteracted[msg.sender]) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * totalBluesStakedPerAddress[msg.sender] * userMultiplier[msg.sender]) / 1 days; if (legendryHoldingsPerUser[msg.sender] > 0) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * (legendryHoldingsPerUser[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) / 1 days; } lastInteractionTimeStamp[msg.sender] = block.timestamp; } _; } function getDailyYield(address account) external view returns (uint256) { uint256 yeild = (totalBluesStakedPerAddress[account] * userMultiplier[account]); yeild += (legendryHoldingsPerUser[account] * DAILY_WHALES_RATE_LEGENDRY); return yeild; } function getOcean() external view returns (address[5600] memory) { return ocean; } function setBlues(address _blues) external onlyOwner { Blues = IERC721(_blues); } function setWhales(address _whales) external onlyOwner { Whales = IWhales(_whales); } function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { return this.onERC721Received.selector; } }
6,943,691
pragma solidity ^0.6.2; import "./node_modules/@openzeppelin/contracts/access/Ownable.sol"; import "./node_modules/@openzeppelin/contracts/math/SafeMath.sol"; import "./facades/LachesisLike.sol"; import "./facades/ScarcityLike.sol"; import "./facades/BehodlerLike.sol"; import "./libraries/SafeOperations.sol"; import "./facades/ERC20Like.sol"; import "./facades/JanusLike.sol"; import "./facades/WethLike.sol"; import "./facades/PyroTokenRegistryLike.sol"; /* Miruvor is a low gas alternative to buying Scarcity straight from Behodler The price per unit is higher than on Behodler and the amount of Scarcity is limited. When Scarcity is purchased, the contract by definition fills with trading tokens. A top up function exists to flush the tokens by calling Behodler.buy(). Purchasing SCX creates Pyrotokens. Instead of keeping them, the contract redeems them and pays them to caller to compensate for gas. The markup should be set such that Miruvor profits, thereby growing the pool of SCX over time and being increasingly rewarding to end users. */ contract Miruvor is Ownable { LachesisLike public lachesis; BehodlerLike public behodler; ScarcityLike public scarcity; JanusLike public janus; WethLike public weth; PyroTokenRegistryLike public pyroTokenRegistry; ERC20Like public dai; ERC20Like public weiDai; uint256 public discount = 900; // divide by 1000 to get multiplier. 900 = 0.9 using SafeMath for uint256; using SafeOperations for uint256; mapping(address => uint256) public SCXperToken; //SCALED BY ONE uint256 constant ONE = 1 ether; uint256 constant factor = 128; function setMarkup(uint256 d) public onlyOwner { require(d <= 1000, "1000 === 1"); discount = d; } function seed( address scx, address behodlerAddress, address lachesisAddress, address janusAddress, address wethAddress, address pTokenReg, address daiAddress, address weiDaiAddress ) public onlyOwner { lachesis = LachesisLike(lachesisAddress); scarcity = ScarcityLike(scx); behodler = BehodlerLike(behodlerAddress); janus = JanusLike(janusAddress); weth = WethLike(wethAddress); pyroTokenRegistry = PyroTokenRegistryLike(pTokenReg); dai = ERC20Like(daiAddress); weiDai = ERC20Like(weiDaiAddress); } function canDrink(address tokenAddress) public returns (bool) { if (!lachesis.tokens(tokenAddress) || SCXperToken[tokenAddress] == 0) return false; } function refresh(address tokenAddress) public { SCXperToken[tokenAddress] = calculateSCXperToken( tokenAddress, scarcity.balanceOf(address(this)) ) .mul(discount) .div(1000); } //purchases SCX with token function drink(address tokenAddress, uint256 value) public { drink(tokenAddress, value, msg.sender); } //user enables weth for Miruvor function drinkEth() public payable { require(msg.value > 0, "no eth sent"); weth.deposit.value(msg.value)(); weth.transfer(msg.sender, msg.value); drink(address(weth), msg.value, msg.sender); } function drink( address tokenAddress, uint256 value, address sender ) private { require(canDrink(tokenAddress), "Invalid token. Try refreshing."); uint256 scx = SCXperToken[tokenAddress].mul(value).div(ONE); require( ERC20Like(tokenAddress).transferFrom(sender, address(this), value), "token transfer failed" ); require(scarcity.transfer(sender, scx), "scarcity payout failed"); } function stopperEth() public payable { janus.ethToToken{value: msg.value}(address(scarcity), 0, 0); ERC20Like pToken = ERC20Like( pyroTokenRegistry.baseTokenMapping(address(weth)) ); uint256 pbalance = pToken.balanceOf(address(this)); pToken.transfer(msg.sender, pbalance); refresh(address(weth)); } //flushes the token balance into Behodler, pays caller fee function stopper(address tokenAddress) public { if (tokenAddress == address(dai) || tokenAddress == address(weiDai)) { uint256 tokenBalanceBefore = ERC20Like(tokenAddress).balanceOf( address(this) ); ERC20Like(tokenAddress).transfer( msg.sender, tokenBalanceBefore / 100 ); uint256 tokenBalanceAfter = ERC20Like(tokenAddress).balanceOf( address(this) ); janus.tokenToToken( tokenAddress, address(scarcity), tokenBalanceAfter, 0, 0 ); } else { uint256 tokenBalance = ERC20Like(tokenAddress).balanceOf( address(this) ); ERC20Like pToken = ERC20Like( pyroTokenRegistry.baseTokenMapping(tokenAddress) ); janus.tokenToToken( tokenAddress, address(scarcity), tokenBalance, 0, 0 ); uint256 pbalance = pToken.balanceOf(address(this)); pToken.transfer(msg.sender, pbalance); } refresh(tokenAddress); } //Given a level of SCX, how many tokens are required to generate it function calculateSCXperToken(address tokenAddress, uint256 scx) public view returns (uint256) { uint256 tokensToPurchaseWith = scx.square() + scx.mul(behodler.tokenScarcityObligations(tokenAddress)).mul(2); return scx.mul(ONE).div(tokensToPurchaseWith); } }
flushes the token balance into Behodler, pays caller fee
function stopper(address tokenAddress) public { if (tokenAddress == address(dai) || tokenAddress == address(weiDai)) { uint256 tokenBalanceBefore = ERC20Like(tokenAddress).balanceOf( address(this) ); ERC20Like(tokenAddress).transfer( msg.sender, tokenBalanceBefore / 100 ); uint256 tokenBalanceAfter = ERC20Like(tokenAddress).balanceOf( address(this) ); janus.tokenToToken( tokenAddress, address(scarcity), tokenBalanceAfter, 0, 0 ); uint256 tokenBalance = ERC20Like(tokenAddress).balanceOf( address(this) ); ERC20Like pToken = ERC20Like( pyroTokenRegistry.baseTokenMapping(tokenAddress) ); janus.tokenToToken( tokenAddress, address(scarcity), tokenBalance, 0, 0 ); uint256 pbalance = pToken.balanceOf(address(this)); pToken.transfer(msg.sender, pbalance); } refresh(tokenAddress); }
13,115,922
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol"; import "./inheritables/Moduleable.sol"; import "./interfaces/ITransferValidator.sol"; contract AssetToken is MintableToken, BurnableToken, Moduleable { /*----------- Events -----------*/ event ForceTransfer( address indexed from, address indexed to, address indexed owner, uint256 value, bytes data ); /*----------- Globals -----------*/ bool internal _initialized = false; string public name; uint8 public decimals; string public symbol; string public version = "0.3"; uint8 public constant TRANSFER_VALIDATOR_TYPE = 1; /*----------- Modifiers -----------*/ modifier onlyInitialized() { require(_initialized, "onlyInitialized"); _; } modifier onlyNotInitialized() { require(!_initialized, "onlyNotInitialized"); _; } modifier validDestination( address to ) { require(to != address(0x0), "Cannot transfer to 0 address"); require(to != address(this), "Cannot transfer to self"); _; } /*----------- initialize -----------*/ function initialize( address _owner, uint256 _initialAmount, string _name, uint8 _decimalUnits, string _symbol ) external onlyNotInitialized { require(!_initialized, "Already Initialized"); owner = _owner; name = _name; decimals = _decimalUnits; symbol = _symbol; totalSupply_ = _initialAmount; balances[owner] = _initialAmount; emit Transfer(address(0), owner, totalSupply_); _initialized = true; } /** * @dev Change the name * @param _name new string for the name */ function changeName(string _name) external onlyOwner onlyInitialized returns( bool success ) { name = _name; return true; } /** * @dev Change the token symbol * @param _symbol new string for the symbol */ function changeSymbol(string _symbol) external onlyOwner onlyInitialized returns( bool success ) { symbol = _symbol; return true; } /*----------- Transfer Methods -----------*/ /** * @dev Transfer tokens from sender's address to another * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transfer(address _to, uint256 _value) public validDestination(_to) returns (bool success) { require(canSend(msg.sender, _to, _value), "Transfer is not valid"); super.transfer(_to, _value); return true; } /** * @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 validDestination(_to) returns (bool success) { require(canSend(_from, _to, _value), "Transfer is not valid"); super.transferFrom(_from, _to, _value); return true; } /** * @dev Force the Transfer of 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 forceTransfer( address _from, address _to, uint256 _value, bytes _data ) public onlyOwner validDestination(_to) returns (bool success) { require(_value <= balances[_from], "_from Address does not have sufficient balance"); require(canSend(_from, _to, _value), "Transfer is not valid"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit ForceTransfer(_from, _to, msg.sender, _value, _data); return true; } /** * @notice validate transfer with TransferValidator module(s) if they exists * @param _from sender of transfer * @param _to receiver of transfer * @param _amount value of transfer * @return bool */ function canSend(address _from, address _to, uint256 _amount) public returns (bool) { if (modules[TRANSFER_VALIDATOR_TYPE].length == 0) { return true; } bool isValid = true; for (uint8 i = 0; i < modules[TRANSFER_VALIDATOR_TYPE].length; i++) { if (modules[TRANSFER_VALIDATOR_TYPE][i] != address(0)) { isValid = ITransferValidator( modules[TRANSFER_VALIDATOR_TYPE][i] ).canSend(this, _from, _to, _amount); } if (!isValid) { break; } } return isValid; } /*----------- Burn Methods -----------*/ /** * @dev Burn tokens from sender's address - adding onlyOwner modifier * @param _value uint256 the amount of tokens to be transferred */ function burn(uint256 _value) public onlyOwner { super.burn(_value); } /** * @dev Burn tokens from a non-sender address * @param _who token holder whose tokens are being burned * @param _value uint256 the amount of tokens to be transferred */ function burnFrom(address _who, uint256 _value) public onlyOwner { _burn(_who, _value); } }
validate transfer with TransferValidator module(s) if they exists _from sender of transfer _to receiver of transfer _amount value of transfer return bool/
function canSend(address _from, address _to, uint256 _amount) public returns (bool) { if (modules[TRANSFER_VALIDATOR_TYPE].length == 0) { return true; } bool isValid = true; for (uint8 i = 0; i < modules[TRANSFER_VALIDATOR_TYPE].length; i++) { if (modules[TRANSFER_VALIDATOR_TYPE][i] != address(0)) { isValid = ITransferValidator( modules[TRANSFER_VALIDATOR_TYPE][i] ).canSend(this, _from, _to, _amount); } if (!isValid) { break; } } return isValid; }
15,838,301
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol"; import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol"; import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol"; import {CoreRef} from "../refs/CoreRef.sol"; import {ICore} from "../core/ICore.sol"; import {Core} from "../core/Core.sol"; import {TribeRoles} from "../core/TribeRoles.sol"; import {IPodAdminGateway} from "./interfaces/IPodAdminGateway.sol"; import {IPodFactory} from "./interfaces/IPodFactory.sol"; /// @title PodAdminGateway for TRIBE Governance pods /// @notice Acts as a gateway for admin functionality and vetos in the TRIBE governance pod system /// @dev Contract is intended to be set as the podAdmin for all deployed Orca pods. Specifically enables: /// 1. Adding a member to a pod /// 2. Removing a member from a pod /// 3. Transferring a pod member /// 4. Toggling a pod membership transfer switch /// 5. Vetoing a pod proposal contract PodAdminGateway is CoreRef, IPodAdminGateway { /// @notice Orca membership token for the pods. Handles permissioning pod members MemberToken private immutable memberToken; /// @notice Pod factory which creates optimistic pods and acts as a source of information IPodFactory public immutable podFactory; constructor( address _core, address _memberToken, address _podFactory ) CoreRef(_core) { memberToken = MemberToken(_memberToken); podFactory = IPodFactory(_podFactory); } //////////////////////// GETTERS //////////////////////////////// /// @notice Calculate the specific pod admin role identifier /// @dev This role is able to add pod members, remove pod members, lock and unlock transfers and veto /// proposals function getSpecificPodAdminRole(uint256 _podId) public pure override returns (bytes32) { return keccak256(abi.encode(_podId, "_ORCA_POD", "_ADMIN")); } /// @notice Calculate the specific pod guardian role identifier /// @dev This role is able to remove pod members and veto pod proposals function getSpecificPodGuardianRole(uint256 _podId) public pure override returns (bytes32) { return keccak256(abi.encode(_podId, "_ORCA_POD", "_GUARDIAN")); } ///////////////////////// ADMIN PRIVILEDGES //////////////////////////// /// @notice Admin functionality to add a member to a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADD_MEMBER_ROLE function addPodMember(uint256 _podId, address _member) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _addMemberToPod(_podId, _member); } /// @notice Internal method to add a member to a pod function _addMemberToPod(uint256 _podId, address _member) internal { emit AddPodMember(_podId, _member); memberToken.mint(_member, _podId, bytes("")); } /// @notice Admin functionality to batch add a member to a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADMIN_REMOVE_MEMBER function batchAddPodMember(uint256 _podId, address[] calldata _members) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { uint256 numMembers = _members.length; for (uint256 i = 0; i < numMembers; ) { _addMemberToPod(_podId, _members[i]); // i is constrained by being < _members.length unchecked { i += 1; } } } /// @notice Admin functionality to remove a member from a pod. /// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER function removePodMember(uint256 _podId, address _member) external override hasAnyOfFiveRoles( TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, TribeRoles.GUARDIAN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { _removePodMember(_podId, _member); } /// @notice Internal method to remove a member from a pod function _removePodMember(uint256 _podId, address _member) internal { emit RemovePodMember(_podId, _member); memberToken.burn(_member, _podId); } /// @notice Admin functionality to batch remove a member from a pod /// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER function batchRemovePodMember(uint256 _podId, address[] calldata _members) external override hasAnyOfFiveRoles( TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, TribeRoles.GUARDIAN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { uint256 numMembers = _members.length; for (uint256 i = 0; i < numMembers; ) { _removePodMember(_podId, _members[i]); // i is constrained by being < _members.length unchecked { i += 1; } } } /// @notice Admin functionality to turn off pod membership transfer /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function lockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, true); } /// @notice Admin functionality to turn on pod membership transfers /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function unlockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, false); } /// @notice Internal method to toggle a pod membership transfer lock function _setMembershipTransferLock(uint256 _podId, bool _lock) internal { ControllerV1 podController = ControllerV1(memberToken.memberController(_podId)); podController.setPodTransferLock(_podId, _lock); emit PodMembershipTransferLock(_podId, _lock); } /// @notice Transfer the admin of a pod to a new address /// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role function transferAdmin(uint256 _podId, address _newAdmin) external hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { ControllerV1 podController = ControllerV1(memberToken.memberController(_podId)); address oldPodAdmin = podController.podAdmin(_podId); podController.updatePodAdmin(_podId, _newAdmin); emit UpdatePodAdmin(_podId, oldPodAdmin, _newAdmin); } /////////////// VETO CONTROLLER ///////////////// /// @notice Allow a proposal to be vetoed in a pod timelock /// @dev Permissioned to GOVERNOR, POD_VETO_ADMIN, GUARDIAN, POD_ADMIN and the specific /// pod admin and guardian roles function veto(uint256 _podId, bytes32 _proposalId) external override hasAnyOfSixRoles( TribeRoles.GOVERNOR, TribeRoles.POD_VETO_ADMIN, TribeRoles.GUARDIAN, TribeRoles.POD_ADMIN, getSpecificPodGuardianRole(_podId), getSpecificPodAdminRole(_podId) ) { address _podTimelock = podFactory.getPodTimelock(_podId); emit VetoTimelock(_podId, _podTimelock, _proposalId); TimelockController(payable(_podTimelock)).cancel(_proposalId); } } pragma solidity 0.8.7; /* solhint-disable indent */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "./interfaces/IControllerRegistry.sol"; import "./interfaces/IControllerBase.sol"; contract MemberToken is ERC1155Supply, Ownable { using Address for address; IControllerRegistry public controllerRegistry; mapping(uint256 => address) public memberController; uint256 public nextAvailablePodId = 0; string public _contractURI = "https://orcaprotocol-nft.vercel.app/assets/contract-metadata"; event MigrateMemberController(uint256 podId, address newController); /** * @param _controllerRegistry The address of the ControllerRegistry contract */ constructor(address _controllerRegistry, string memory uri) ERC1155(uri) { require(_controllerRegistry != address(0), "Invalid address"); controllerRegistry = IControllerRegistry(_controllerRegistry); } // Provides metadata value for the opensea wallet. Must be set at construct time // Source: https://www.reddit.com/r/ethdev/comments/q4j5bf/contracturi_not_reflected_in_opensea/ function contractURI() public view returns (string memory) { return _contractURI; } // Note that OpenSea does not currently update contract metadata when this value is changed. - Nov 2021 function setContractURI(string memory newContractURI) public onlyOwner { _contractURI = newContractURI; } /** * @param _podId The pod id number * @param _newController The address of the new controller */ function migrateMemberController(uint256 _podId, address _newController) external { require(_newController != address(0), "Invalid address"); require( msg.sender == memberController[_podId], "Invalid migrate controller" ); require( controllerRegistry.isRegistered(_newController), "Controller not registered" ); memberController[_podId] = _newController; emit MigrateMemberController(_podId, _newController); } function getNextAvailablePodId() external view returns (uint256) { return nextAvailablePodId; } function setUri(string memory uri) external onlyOwner { _setURI(uri); } /** * @param _account The account address to assign the membership token to * @param _id The membership token id to mint * @param data Passes a flag for initial creation event */ function mint( address _account, uint256 _id, bytes memory data ) external { _mint(_account, _id, 1, data); } /** * @param _accounts The account addresses to assign the membership tokens to * @param _id The membership token id to mint * @param data Passes a flag for an initial creation event */ function mintSingleBatch( address[] memory _accounts, uint256 _id, bytes memory data ) public { for (uint256 index = 0; index < _accounts.length; index += 1) { _mint(_accounts[index], _id, 1, data); } } /** * @param _accounts The account addresses to burn the membership tokens from * @param _id The membership token id to burn */ function burnSingleBatch(address[] memory _accounts, uint256 _id) public { for (uint256 index = 0; index < _accounts.length; index += 1) { _burn(_accounts[index], _id, 1); } } function createPod(address[] memory _accounts, bytes memory data) external returns (uint256) { uint256 id = nextAvailablePodId; nextAvailablePodId += 1; require( controllerRegistry.isRegistered(msg.sender), "Controller not registered" ); memberController[id] = msg.sender; if (_accounts.length != 0) { mintSingleBatch(_accounts, id, data); } return id; } /** * @param _account The account address holding the membership token to destroy * @param _id The id of the membership token to destroy */ function burn(address _account, uint256 _id) external { _burn(_account, _id, 1); } // this hook gets called before every token event including mint and burn /** * @param operator The account address that initiated the action * @param from The account address recieveing the membership token * @param to The account address sending the membership token * @param ids An array of membership token ids to be transfered * @param amounts The amount of each membership token type to transfer * @param data Passes a flag for an initial creation event */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { // use first id to lookup controller address controller = memberController[ids[0]]; require(controller != address(0), "Pod doesn't exist"); for (uint256 i = 0; i < ids.length; i += 1) { // check if recipient is already member if (to != address(0)) { require(balanceOf(to, ids[i]) == 0, "User is already member"); } // verify all ids use same controller require( memberController[ids[i]] == controller, "Ids have different controllers" ); } // perform orca token transfer validations IControllerBase(controller).beforeTokenTransfer( operator, from, to, ids, amounts, data ); } } pragma solidity 0.8.7; /* solhint-disable indent */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/IControllerV1.sol"; import "./interfaces/IMemberToken.sol"; import "./interfaces/IControllerRegistry.sol"; import "./SafeTeller.sol"; import "./ens/IPodEnsRegistrar.sol"; contract ControllerV1 is IControllerV1, SafeTeller, Ownable { event CreatePod(uint256 podId, address safe, address admin, string ensName); event UpdatePodAdmin(uint256 podId, address admin); IMemberToken public immutable memberToken; IControllerRegistry public immutable controllerRegistry; IPodEnsRegistrar public podEnsRegistrar; string public constant VERSION = "1.2.0"; mapping(address => uint256) public safeToPodId; mapping(uint256 => address) public podIdToSafe; mapping(uint256 => address) public podAdmin; mapping(uint256 => bool) public isTransferLocked; uint8 internal constant CREATE_EVENT = 0x01; /** * @dev Will instantiate safe teller with gnosis master and proxy addresses * @param _memberToken The address of the MemberToken contract * @param _controllerRegistry The address of the ControllerRegistry contract * @param _proxyFactoryAddress The proxy factory address * @param _gnosisMasterAddress The gnosis master address */ constructor( address _memberToken, address _controllerRegistry, address _proxyFactoryAddress, address _gnosisMasterAddress, address _podEnsRegistrar, address _fallbackHandlerAddress ) SafeTeller( _proxyFactoryAddress, _gnosisMasterAddress, _fallbackHandlerAddress ) { require(_memberToken != address(0), "Invalid address"); require(_controllerRegistry != address(0), "Invalid address"); require(_proxyFactoryAddress != address(0), "Invalid address"); require(_gnosisMasterAddress != address(0), "Invalid address"); require(_podEnsRegistrar != address(0), "Invalid address"); require(_fallbackHandlerAddress != address(0), "Invalid address"); memberToken = IMemberToken(_memberToken); controllerRegistry = IControllerRegistry(_controllerRegistry); podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar); } function updatePodEnsRegistrar(address _podEnsRegistrar) external override onlyOwner { require(_podEnsRegistrar != address(0), "Invalid address"); podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar); } /** * @param _members The addresses of the members of the pod * @param threshold The number of members that are required to sign a transaction * @param _admin The address of the pod admin * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPod( address[] memory _members, uint256 threshold, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external override { address safe = createSafe(_members, threshold); _createPod( _members, safe, _admin, _label, _ensString, expectedPodId, _imageUrl ); } /** * @dev Used to create a pod with an existing safe * @dev Will automatically distribute membership NFTs to current safe members * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPodWithSafe( address _admin, address _safe, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external override { require(_safe != address(0), "invalid safe address"); require(safeToPodId[_safe] == 0, "safe already in use"); require(isSafeModuleEnabled(_safe), "safe module must be enabled"); require( isSafeMember(_safe, msg.sender) || msg.sender == _safe, "caller must be safe or member" ); address[] memory members = getSafeMembers(_safe); _createPod( members, _safe, _admin, _label, _ensString, expectedPodId, _imageUrl ); } /** * @param _members The addresses of the members of the pod * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function _createPod( address[] memory _members, address _safe, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) private { // add create event flag to token data bytes memory data = new bytes(1); data[0] = bytes1(uint8(CREATE_EVENT)); uint256 podId = memberToken.createPod(_members, data); // The imageUrl has an expected pod ID, but we need to make sure it aligns with the actual pod ID require(podId == expectedPodId, "pod id didn't match, try again"); emit CreatePod(podId, _safe, _admin, _ensString); emit UpdatePodAdmin(podId, _admin); if (_admin != address(0)) { // will lock safe modules if admin exists setModuleLock(_safe, true); podAdmin[podId] = _admin; } podIdToSafe[podId] = _safe; safeToPodId[_safe] = podId; // setup pod ENS address reverseRegistrar = podEnsRegistrar.registerPod( _label, _safe, msg.sender ); setupSafeReverseResolver(_safe, reverseRegistrar, _ensString); // Node is how ENS identifies names, we need that to setText bytes32 node = podEnsRegistrar.getEnsNode(_label); podEnsRegistrar.setText(node, "avatar", _imageUrl); podEnsRegistrar.setText(node, "podId", Strings.toString(podId)); } /** * @dev Allows admin to unlock the safe modules and allow them to be edited by members * @param _podId The id number of the pod * @param _isLocked true - pod modules cannot be added/removed */ function setPodModuleLock(uint256 _podId, bool _isLocked) external override { require( msg.sender == podAdmin[_podId], "Must be admin to set module lock" ); setModuleLock(podIdToSafe[_podId], _isLocked); } /** * @param _podId The id number of the pod * @param _newAdmin The address of the new pod admin */ function updatePodAdmin(uint256 _podId, address _newAdmin) external override { address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; require(safe != address(0), "Pod doesn't exist"); // if there is no admin it can only be added by safe if (admin == address(0)) { require(msg.sender == safe, "Only safe can add new admin"); } else { require(msg.sender == admin, "Only admin can update admin"); } // set module lock to true for non zero _newAdmin setModuleLock(safe, _newAdmin != address(0)); podAdmin[_podId] = _newAdmin; emit UpdatePodAdmin(_podId, _newAdmin); } /** * @param _podId The id number of the pod * @param _isTransferLocked The address of the new pod admin */ function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external override { address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; // if no pod admin it can only be set by safe if (admin == address(0)) { require(msg.sender == safe, "Only safe can set transfer lock"); } else { // if admin then it can be set by admin or safe require( msg.sender == admin || msg.sender == safe, "Only admin or safe can set transfer lock" ); } // set podid to transfer lock bool isTransferLocked[_podId] = _isTransferLocked; } /** * @dev This will nullify all pod state on this controller * @dev Update state on _newController * @dev Update controller to _newController in Safe and MemberToken * @param _podId The id number of the pod * @param _newController The address of the new pod controller * @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list */ function migratePodController( uint256 _podId, address _newController, address _prevModule ) external override { require(_newController != address(0), "Invalid address"); require( controllerRegistry.isRegistered(_newController), "Controller not registered" ); address admin = podAdmin[_podId]; address safe = podIdToSafe[_podId]; require( msg.sender == admin || msg.sender == safe, "User not authorized" ); IControllerBase newController = IControllerBase(_newController); // nullify current pod state podAdmin[_podId] = address(0); podIdToSafe[_podId] = address(0); safeToPodId[safe] = 0; // update controller in MemberToken memberToken.migrateMemberController(_podId, _newController); // update safe module to _newController migrateSafeTeller(safe, _newController, _prevModule); // update pod state in _newController newController.updatePodState(_podId, admin, safe); } /** * @dev This is called by another version of controller to migrate a pod to this version * @dev Will only accept calls from registered controllers * @dev Can only be called once. * @param _podId The id number of the pod * @param _podAdmin The address of the pod admin * @param _safeAddress The address of the safe */ function updatePodState( uint256 _podId, address _podAdmin, address _safeAddress ) external override { require(_safeAddress != address(0), "Invalid address"); require( controllerRegistry.isRegistered(msg.sender), "Controller not registered" ); require( podAdmin[_podId] == address(0) && podIdToSafe[_podId] == address(0) && safeToPodId[_safeAddress] == 0, "Pod already exists" ); // if there is a pod admin, set state and lock modules if (_podAdmin != address(0)) { podAdmin[_podId] = _podAdmin; setModuleLock(_safeAddress, true); } podIdToSafe[_podId] = _safeAddress; safeToPodId[_safeAddress] = _podId; setSafeTellerAsGuard(_safeAddress); emit UpdatePodAdmin(_podId, _podAdmin); } /** * @param operator The address that initiated the action * @param from The address sending the membership token * @param to The address recieveing the membership token * @param ids An array of membership token ids to be transfered * @param data Passes a flag for an initial creation event */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory, bytes memory data ) external override { require(msg.sender == address(memberToken), "Not Authorized"); // if create event than side effects have been pre-handled // only recognise data flags from this controller if (operator == address(this) && uint8(data[0]) == CREATE_EVENT) return; for (uint256 i = 0; i < ids.length; i += 1) { uint256 podId = ids[i]; address safe = podIdToSafe[podId]; address admin = podAdmin[podId]; if (from == address(0)) { // mint event // there are no rules operator must be admin, safe or controller require( operator == safe || operator == admin || operator == address(this), "No Rules Set" ); onMint(to, safe); } else if (to == address(0)) { // burn event // there are no rules operator must be admin, safe or controller require( operator == safe || operator == admin || operator == address(this), "No Rules Set" ); onBurn(from, safe); } else { // pod cannot be locked require( isTransferLocked[podId] == false, "Pod Is Transfer Locked" ); // transfer event onTransfer(from, to, safe); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (governance/TimelockController.sol) pragma solidity ^0.8.0; import "../access/AccessControl.sol"; import "../token/ERC721/IERC721Receiver.sol"; import "../token/ERC1155/IERC1155Receiver.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`, and a list of * initial proposers and executors. The proposers receive both the * proposer and the canceller role (for backward compatibility). The * executors receive the executor role. * * NOTE: At construction, both the deployer and the timelock itself are * administrators. This helps further configuration of the timelock by the * deployer. After configuration is done, it is recommended that the * deployer renounces its admin position and relies on timelocked * operations to perform future maintenance. */ constructor( uint256 minDelay, address[] memory proposers, address[] memory executors ) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers and cancellers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); _setupRole(CANCELLER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, payloads, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'canceller' role. */ function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function execute( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(id, predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _beforeCall(id, predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], payloads[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 id, bytes32 predecessor) private view { require(isOperationReady(id), "TimelockController: operation is not ready"); require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call( bytes32 id, uint256 index, address target, uint256 value, bytes calldata data ) private { (bool success, ) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } /** * @dev See {IERC721Receiver-onERC721Received}. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155Received}. */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155BatchReceived}. */ function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IFei private immutable _fei; IERC20 private immutable _tribe; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _fei = ICore(coreAddress).fei(); _tribe = ICore(coreAddress).tribe(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize(address) internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require(_core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller"); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require(_core.isGovernor(msg.sender), "CoreRef: Caller is not a governor"); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin" ); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; } modifier hasAnyOfThreeRoles( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFourRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFiveRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfSixRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5, bytes32 role6 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender) || _core.hasRole(role6, msg.sender), "UNAUTHORIZED" ); _; } modifier onlyFei() { require(msg.sender == address(_fei), "CoreRef: Caller is not FEI"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _fei; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _tribe; } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return _fei.balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return _tribe.balanceOf(address(this)); } function _burnFeiHeld() internal { _fei.burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { _fei.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../fei/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./Permissions.sol"; import "./ICore.sol"; import "../fei/Fei.sol"; import "../tribe/Tribe.sol"; /// @title Source of truth for Fei Protocol /// @author Fei Protocol /// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury contract Core is ICore, Permissions, Initializable { /// @notice the address of the FEI contract IFei public override fei; /// @notice the address of the TRIBE contract IERC20 public override tribe; function init() external override initializer { _setupGovernor(msg.sender); Fei _fei = new Fei(address(this)); _setFei(address(_fei)); Tribe _tribe = new Tribe(address(this), msg.sender); _setTribe(address(_tribe)); } /// @notice sets Fei address to a new address /// @param token new fei address function setFei(address token) external override onlyGovernor { _setFei(token); } /// @notice sets Tribe address to a new address /// @param token new tribe address function setTribe(address token) external override onlyGovernor { _setTribe(token); } /// @notice sends TRIBE tokens from treasury to an address /// @param to the address to send TRIBE to /// @param amount the amount of TRIBE to send function allocateTribe(address to, uint256 amount) external override onlyGovernor { IERC20 _tribe = tribe; require(_tribe.balanceOf(address(this)) >= amount, "Core: Not enough Tribe"); _tribe.transfer(to, amount); emit TribeAllocation(to, amount); } function _setFei(address token) internal { fei = IFei(token); emit FeiUpdate(token); } function _setTribe(address token) internal { tribe = IERC20(token); emit TribeUpdate(token); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /** @title Tribe DAO ACL Roles @notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO. Roles are broken up into 3 categories: * Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed. * Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms * Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs. */ library TribeRoles { /*/////////////////////////////////////////////////////////////// Major Roles //////////////////////////////////////////////////////////////*/ /// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality. bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE"); /// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE"); /// @notice the role which can arbitrarily move PCV in any size from any contract bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE"); /// @notice can mint FEI arbitrarily bytes32 internal constant MINTER = keccak256("MINTER_ROLE"); /// @notice Manages lower level - Admin and Minor - roles. Able to grant and revoke these bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); /*/////////////////////////////////////////////////////////////// Admin Roles //////////////////////////////////////////////////////////////*/ /// @notice has access to all admin functionality on pods bytes32 internal constant POD_ADMIN = keccak256("POD_ADMIN"); /// @notice capable of granting and revoking other TribeRoles from having veto power over a pod bytes32 internal constant POD_VETO_ADMIN = keccak256("POD_VETO_ADMIN"); /// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE. bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN"); /// @notice manages the Collateralization Oracle as well as other protocol oracles. bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE"); /// @notice manages TribalChief incentives and related functionality. bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE"); /// @notice admin of PCVGuardian bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE"); /// @notice admin of all Minor Roles bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN"); /// @notice admin of the Fuse protocol bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN"); /// @notice capable of vetoing DAO votes or optimistic timelocks bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN"); /// @notice capable of setting FEI Minters within global rate limits and caps bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN"); /// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN"); /// @notice manages meta-governance actions, like voting & delegating. /// Also used to vote for gauge weights & similar liquid governance things. bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN"); /// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking /// governance tokens from a pre-defined contract in order to eventually allow voting. /// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV. bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING"); /// @notice manages whitelisting of gauges where the protocol's tokens can be staked bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN"); /*/////////////////////////////////////////////////////////////// Minor Roles //////////////////////////////////////////////////////////////*/ bytes32 internal constant POD_METADATA_REGISTER_ROLE = keccak256("POD_METADATA_REGISTER_ROLE"); /// @notice capable of poking existing LBP auctions to exchange tokens. bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE"); /// @notice capable of engaging with Votium for voting incentives. bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE"); /// @notice capable of adding an address to multi rate limited bytes32 internal constant ADD_MINTER_ROLE = keccak256("ADD_MINTER_ROLE"); /// @notice capable of changing parameters within non-critical ranges bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE"); /// @notice capable of changing PCV Deposit and Global Rate Limited Minter in the PSM bytes32 internal constant PSM_ADMIN_ROLE = keccak256("PSM_ADMIN_ROLE"); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPodAdminGateway { event AddPodMember(uint256 indexed podId, address member); event RemovePodMember(uint256 indexed podId, address member); event UpdatePodAdmin(uint256 indexed podId, address oldPodAdmin, address newPodAdmin); event PodMembershipTransferLock(uint256 indexed podId, bool lock); // Veto functionality event VetoTimelock(uint256 indexed podId, address indexed timelock, bytes32 proposalId); function getSpecificPodAdminRole(uint256 _podId) external pure returns (bytes32); function getSpecificPodGuardianRole(uint256 _podId) external pure returns (bytes32); function addPodMember(uint256 _podId, address _member) external; function batchAddPodMember(uint256 _podId, address[] calldata _members) external; function removePodMember(uint256 _podId, address _member) external; function batchRemovePodMember(uint256 _podId, address[] calldata _members) external; function lockMembershipTransfers(uint256 _podId) external; function unlockMembershipTransfers(uint256 _podId) external; function veto(uint256 _podId, bytes32 proposalId) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol"; import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol"; interface IPodFactory { /// @notice Configuration used when creating a pod /// @param members List of members to be added to the pod /// @param threshold Number of members that need to approve a transaction on the Gnosis safe /// @param label Metadata, Human readable label for the pod /// @param ensString Metadata, ENS name of the pod /// @param imageUrl Metadata, URL to a image to represent the pod in frontends /// @param minDelay Delay on the timelock struct PodConfig { address[] members; uint256 threshold; bytes32 label; string ensString; string imageUrl; address admin; uint256 minDelay; } event CreatePod(uint256 indexed podId, address indexed safeAddress, address indexed timelock); event CreateTimelock(address indexed timelock); event UpdatePodController(address indexed oldController, address indexed newController); event UpdateDefaultPodController(address indexed oldController, address indexed newController); function deployCouncilPod(PodConfig calldata _config) external returns ( uint256, address, address ); function defaultPodController() external view returns (ControllerV1); function getMemberToken() external view returns (MemberToken); function getPodSafeAddresses() external view returns (address[] memory); function getNumberOfPods() external view returns (uint256); function getPodController(uint256 podId) external view returns (ControllerV1); function getPodSafe(uint256 podId) external view returns (address); function getPodTimelock(uint256 podId) external view returns (address); function getNumMembers(uint256 podId) external view returns (uint256); function getPodMembers(uint256 podId) external view returns (address[] memory); function getPodThreshold(uint256 podId) external view returns (uint256); function getIsMembershipTransferLocked(uint256 podId) external view returns (bool); function getNextPodId() external view returns (uint256); function getPodAdmin(uint256 podId) external view returns (address); function createOptimisticPod(PodConfig calldata _config) external returns ( uint256, address, address ); function updateDefaultPodController(address _newDefaultController) external; } // 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 (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 (last updated v4.6.0) (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.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 ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address 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}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).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 { _setApprovalForAll(_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(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, to, ids, amounts, 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); _afterTokenTransfer(operator, from, to, ids, amounts, data); _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); _afterTokenTransfer(operator, from, to, ids, amounts, data); _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 `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, address(0), to, 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); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); 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: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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 {} /** * @dev Hook that is called after 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 _afterTokenTransfer( 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 IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.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 IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 supply = _totalSupply[id]; require(supply >= amount, "ERC1155: burn amount exceeds totalSupply"); unchecked { _totalSupply[id] = supply - amount; } } } } } pragma solidity 0.8.7; interface IControllerRegistry{ /** * @param _controller Address to check if registered as a controller * @return Boolean representing if the address is a registered as a controller */ function isRegistered(address _controller) external view returns (bool); } pragma solidity 0.8.7; interface IControllerBase { /** * @param operator The account address that initiated the action * @param from The account address sending the membership token * @param to The account address recieving the membership token * @param ids An array of membership token ids to be transfered * @param amounts The amount of each membership token type to transfer * @param data Arbitrary data */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; function updatePodState( uint256 _podId, address _podAdmin, address _safeAddress ) external; } // 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/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.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 IERC1155 is IERC165 { /** * @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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @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. * * NOTE: 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. * * NOTE: 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.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 IERC1155MetadataURI is IERC1155 { /** * @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 // 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 // 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); } } pragma solidity 0.8.7; import "./IControllerBase.sol"; interface IControllerV1 is IControllerBase { function updatePodEnsRegistrar(address _podEnsRegistrar) external; /** * @param _members The addresses of the members of the pod * @param threshold The number of members that are required to sign a transaction * @param _admin The address of the pod admin * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPod( address[] memory _members, uint256 threshold, address _admin, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external; /** * @dev Used to create a pod with an existing safe * @dev Will automatically distribute membership NFTs to current safe members * @param _admin The address of the pod admin * @param _safe The address of existing safe * @param _label label hash of pod name (i.e labelhash('mypod')) * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function createPodWithSafe( address _admin, address _safe, bytes32 _label, string memory _ensString, uint256 expectedPodId, string memory _imageUrl ) external; /** * @dev Allows admin to unlock the safe modules and allow them to be edited by members * @param _podId The id number of the pod * @param _isLocked true - pod modules cannot be added/removed */ function setPodModuleLock(uint256 _podId, bool _isLocked) external; /** * @param _podId The id number of the pod * @param _isTransferLocked The address of the new pod admin */ function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external; /** * @param _podId The id number of the pod * @param _newAdmin The address of the new pod admin */ function updatePodAdmin(uint256 _podId, address _newAdmin) external; /** * @dev This will nullify all pod state on this controller * @dev Update state on _newController * @dev Update controller to _newController in Safe and MemberToken * @param _podId The id number of the pod * @param _newController The address of the new pod controller * @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list */ function migratePodController( uint256 _podId, address _newController, address _prevModule ) external; } pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface IMemberToken is IERC1155 { /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) external view returns (uint256); /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) external view returns (bool); function getNextAvailablePodId() external view returns (uint256); /** * @param _podId The pod id number * @param _newController The address of the new controller */ function migrateMemberController(uint256 _podId, address _newController) external; /** * @param _account The account address to transfer the membership token to * @param _id The membership token id to mint * @param data Arbitrary data */ function mint( address _account, uint256 _id, bytes memory data ) external; /** * @param _accounts The account addresses to transfer the membership tokens to * @param _id The membership token id to mint * @param data Arbitrary data */ function mintSingleBatch( address[] memory _accounts, uint256 _id, bytes memory data ) external; function createPod(address[] memory _accounts, bytes memory data) external returns (uint256); } pragma solidity 0.8.7; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IGnosisSafe.sol"; import "./interfaces/IGnosisSafeProxyFactory.sol"; import "@gnosis.pm/zodiac/contracts/guard/BaseGuard.sol"; contract SafeTeller is BaseGuard { using Address for address; // mainnet: 0x76E2cFc1F5Fa8F6a5b3fC4c8F4788F0116861F9B; address public immutable proxyFactoryAddress; // mainnet: 0x34CfAC646f301356fAa8B21e94227e3583Fe3F5F; address public immutable gnosisMasterAddress; address public immutable fallbackHandlerAddress; string public constant FUNCTION_SIG_SETUP = "setup(address[],uint256,address,bytes,address,address,uint256,address)"; string public constant FUNCTION_SIG_EXEC = "execTransaction(address,uint256,bytes,uint8,uint256,uint256,uint256,address,address,bytes)"; string public constant FUNCTION_SIG_ENABLE = "delegateSetup(address)"; bytes4 public constant ENCODED_SIG_ENABLE_MOD = bytes4(keccak256("enableModule(address)")); bytes4 public constant ENCODED_SIG_DISABLE_MOD = bytes4(keccak256("disableModule(address,address)")); bytes4 public constant ENCODED_SIG_SET_GUARD = bytes4(keccak256("setGuard(address)")); address internal constant SENTINEL = address(0x1); // pods with admin have modules locked by default mapping(address => bool) public areModulesLocked; /** * @param _proxyFactoryAddress The proxy factory address * @param _gnosisMasterAddress The gnosis master address */ constructor( address _proxyFactoryAddress, address _gnosisMasterAddress, address _fallbackHanderAddress ) { proxyFactoryAddress = _proxyFactoryAddress; gnosisMasterAddress = _gnosisMasterAddress; fallbackHandlerAddress = _fallbackHanderAddress; } /** * @param _safe The address of the safe * @param _newSafeTeller The address of the new safe teller contract */ function migrateSafeTeller( address _safe, address _newSafeTeller, address _prevModule ) internal { // add new safeTeller bytes memory enableData = abi.encodeWithSignature( "enableModule(address)", _newSafeTeller ); bool enableSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, enableData, IGnosisSafe.Operation.Call ); require(enableSuccess, "Migration failed on enable"); // validate prevModule of current safe teller (address[] memory moduleBuffer, ) = IGnosisSafe(_safe) .getModulesPaginated(_prevModule, 1); require(moduleBuffer[0] == address(this), "incorrect prevModule"); // disable current safeTeller bytes memory disableData = abi.encodeWithSignature( "disableModule(address,address)", _prevModule, address(this) ); bool disableSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, disableData, IGnosisSafe.Operation.Call ); require(disableSuccess, "Migration failed on disable"); } /** * @dev sets the safeteller as safe guard, called after migration * @param _safe The address of the safe */ function setSafeTellerAsGuard(address _safe) internal { bytes memory transferData = abi.encodeWithSignature( "setGuard(address)", address(this) ); bool guardSuccess = IGnosisSafe(_safe).execTransactionFromModule( _safe, 0, transferData, IGnosisSafe.Operation.Call ); require(guardSuccess, "Could not enable guard"); } function getSafeMembers(address safe) public view returns (address[] memory) { return IGnosisSafe(safe).getOwners(); } function isSafeModuleEnabled(address safe) public view returns (bool) { return IGnosisSafe(safe).isModuleEnabled(address(this)); } function isSafeMember(address safe, address member) public view returns (bool) { return IGnosisSafe(safe).isOwner(member); } /** * @param _owners The addresses to be owners of the safe * @param _threshold The number of owners that are required to sign a transaciton * @return safeAddress The address of the new safe */ function createSafe(address[] memory _owners, uint256 _threshold) internal returns (address safeAddress) { bytes memory data = abi.encodeWithSignature( FUNCTION_SIG_ENABLE, address(this) ); // encode the setup call that will be called on the new proxy safe // from the proxy factory bytes memory setupData = abi.encodeWithSignature( FUNCTION_SIG_SETUP, _owners, _threshold, this, data, fallbackHandlerAddress, address(0), uint256(0), address(0) ); try IGnosisSafeProxyFactory(proxyFactoryAddress).createProxy( gnosisMasterAddress, setupData ) returns (address newSafeAddress) { // add safe teller as guard setSafeTellerAsGuard(newSafeAddress); return newSafeAddress; } catch (bytes memory) { revert("Create Proxy With Data Failed"); } } /** * @param to The account address to add as an owner * @param safe The address of the safe */ function onMint(address to, address safe) internal { uint256 threshold = IGnosisSafe(safe).getThreshold(); bytes memory data = abi.encodeWithSignature( "addOwnerWithThreshold(address,uint256)", to, threshold ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @param from The address to be removed as an owner * @param safe The address of the safe */ function onBurn(address from, address safe) internal { uint256 threshold = IGnosisSafe(safe).getThreshold(); address[] memory owners = IGnosisSafe(safe).getOwners(); //look for the address pointing to address from address prevFrom = address(0); for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == from) { if (i == 0) { prevFrom = SENTINEL; } else { prevFrom = owners[i - 1]; } } } if (owners.length - 1 < threshold) threshold -= 1; bytes memory data = abi.encodeWithSignature( "removeOwner(address,address,uint256)", prevFrom, from, threshold ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @param from The address being removed as an owner * @param to The address being added as an owner * @param safe The address of the safe */ function onTransfer( address from, address to, address safe ) internal { address[] memory owners = IGnosisSafe(safe).getOwners(); //look for the address pointing to address from address prevFrom; for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == from) { if (i == 0) { prevFrom = SENTINEL; } else { prevFrom = owners[i - 1]; } } } bytes memory data = abi.encodeWithSignature( "swapOwner(address,address,address)", prevFrom, from, to ); bool success = IGnosisSafe(safe).execTransactionFromModule( safe, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @dev This will execute a tx from the safe that will update the safe's ENS in the reverse resolver * @param safe safe address * @param reverseRegistrar The ENS default reverseRegistar * @param _ensString string of pod ens name (i.e.'mypod.pod.xyz') */ function setupSafeReverseResolver( address safe, address reverseRegistrar, string memory _ensString ) internal { bytes memory data = abi.encodeWithSignature( "setName(string)", _ensString ); bool success = IGnosisSafe(safe).execTransactionFromModule( reverseRegistrar, 0, data, IGnosisSafe.Operation.Call ); require(success, "Module Transaction Failed"); } /** * @dev This will be called by the safe at tx time and prevent module disable on pods with admins * @param safe safe address * @param isLocked safe address */ function setModuleLock(address safe, bool isLocked) internal { areModulesLocked[safe] = isLocked; } /** * @dev This will be called by the safe at execution time time * @param to Destination address of Safe transaction. * @param value Ether value of Safe transaction. * @param data Data payload of Safe transaction. * @param operation Operation type of Safe transaction. * @param safeTxGas Gas that should be used for the Safe transaction. * @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) * @param gasPrice Gas price that should be used for the payment calculation. * @param gasToken Token address (or 0 if ETH) that is used for the payment. * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). * @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) * @param msgSender Account executing safe transaction */ function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external view override { address safe = msg.sender; // if safe isn't locked return if (!areModulesLocked[safe]) return; if (data.length >= 4) { require( bytes4(data) != ENCODED_SIG_ENABLE_MOD, "Cannot Enable Modules" ); require( bytes4(data) != ENCODED_SIG_DISABLE_MOD, "Cannot Disable Modules" ); require( bytes4(data) != ENCODED_SIG_SET_GUARD, "Cannot Change Guard" ); } } function checkAfterExecution(bytes32, bool) external view override {} // TODO: move to library // Used in a delegate call to enable module add on setup function enableModule(address module) external { require(module == address(0)); } function delegateSetup(address _context) external { this.enableModule(_context); } } pragma solidity 0.8.7; interface IPodEnsRegistrar { function getRootNode() external view returns (bytes32); function registerPod( bytes32 label, address podSafe, address podCreator ) external returns (address); function register(bytes32 label, address owner) external; function setText( bytes32 node, string calldata key, string calldata value ) external; function addressToNode(address input) external returns (bytes32); function getEnsNode(bytes32 label) external view returns (bytes32); } pragma solidity 0.8.7; interface IGnosisSafe { enum Operation {Call, DelegateCall} /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes calldata data, Operation operation ) external returns (bool success); /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() external view returns (address[] memory); function isOwner(address owner) external view returns (bool); function getThreshold() external returns (uint256); /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next); /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) external view returns (bool); /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external; } pragma solidity 0.8.7; interface IGnosisSafeProxyFactory { /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param singleton Address of singleton contract. /// @param data Payload for message call sent to new proxy contract. function createProxy(address singleton, bytes memory data) external returns (address); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../interfaces/IGuard.sol"; abstract contract BaseGuard is IERC165 { function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 } /// @dev Module transactions only use the first four parameters: to, value, data, and operation. /// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions. /// @notice This interface is used to maintain compatibilty with Gnosis Safe transaction guards. function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external virtual; function checkAfterExecution(bytes32 txHash, bool success) external virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IGuard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 { 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); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @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 virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.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 virtual 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()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.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 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @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: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @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. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting(address indexed _to, address indexed _minter, uint256 _amount); event Burning(address indexed _to, address indexed _burner, uint256 _amount); event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.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 proxied contracts do not make use of 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. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * 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 prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = _setInitializedVersion(1); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { bool isTopLevelCall = _setInitializedVersion(version); if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(version); } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); } function _setInitializedVersion(uint8 version) private returns (bool) { // 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, and for the lowest level // of initializers, because in other contexts the contract may have been reentered. if (_initializing) { require( version == 1 && !Address.isContract(address(this)), "Initializable: contract is already initialized" ); return false; } else { require(_initialized < version, "Initializable: contract is already initialized"); _initialized = version; return true; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "./IPermissions.sol"; /// @title Access control module for Core /// @author Fei Protocol contract Permissions is IPermissions, AccessControlEnumerable { bytes32 public constant override BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant override MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant override PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant override GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant override GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); constructor() { // Appointed as a governor so guardian can have indirect access to revoke ability _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(GUARDIAN_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require(isGovernor(msg.sender), "Permissions: Caller is not a governor"); _; } modifier onlyGuardian() { require(isGuardian(msg.sender), "Permissions: Caller is not a guardian"); _; } /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } /// @notice grants guardian role to address /// @param guardian new guardian function grantGuardian(address guardian) external override onlyGovernor { grantRole(GUARDIAN_ROLE, guardian); } /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } /// @notice revokes guardian role from address /// @param guardian ex guardian function revokeGuardian(address guardian) external override onlyGovernor { revokeRole(GUARDIAN_ROLE, guardian); } /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external override onlyGuardian { require(role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor"); // External call because this contract is appointed as a governor and has access to revoke this.revokeRole(role, account); } /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view override returns (bool) { return hasRole(MINTER_ROLE, _address); } /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view override returns (bool) { return hasRole(BURNER_ROLE, _address); } /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor // only virtual for testing mock override function isGovernor(address _address) public view virtual override returns (bool) { return hasRole(GOVERN_ROLE, _address); } /// @notice checks if address is a guardian /// @param _address address to check /// @return true _address is a guardian function isGuardian(address _address) public view override returns (bool) { return hasRole(GUARDIAN_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./IIncentive.sol"; import "../refs/CoreRef.sol"; /// @title FEI stablecoin /// @author Fei Protocol contract Fei is IFei, ERC20Burnable, CoreRef { /// @notice get associated incentive contract, 0 address if N/A mapping(address => address) public override incentiveContract; // solhint-disable-next-line var-name-mixedcase 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; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) ERC20("Fei USD", "FEI") CoreRef(core) { uint256 chainId; // solhint-disable-next-line no-inline-assembly 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) ) ); } /// @param account the account to incentivize /// @param incentive the associated incentive contract function setIncentiveContract(address account, address incentive) external override onlyGovernor { incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint256 amount) external override onlyMinter whenNotPaused { _mint(account, amount); emit Minting(account, msg.sender, amount); } /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint256 amount) public override(IFei, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } /// @notice burn FEI tokens from specified account /// @param account the account to burn from /// @param amount the amount to burn function burnFrom(address account, uint256 amount) public override(IFei, ERC20Burnable) onlyBurner whenNotPaused { _burn(account, amount); emit Burning(account, msg.sender, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); _checkAndApplyIncentives(sender, recipient, amount); } function _checkAndApplyIncentives( address sender, address recipient, uint256 amount ) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) { IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount); } // all incentive, if active applies to every transfer address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount); } } /// @notice permit spending of FEI /// @param owner the FEI holder /// @param spender the approved operator /// @param value the amount approved /// @param deadline the deadline after which the approval is no longer valid function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "Fei: 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, "Fei: INVALID_SIGNATURE"); _approve(owner, spender, value); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // Forked from Uniswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBE"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint256 public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @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, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint256 rawAmount) external { require(msg.sender == minter, "Tribe: only the minter can mint"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @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 rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline 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 permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(signatory == owner, "Tribe: unauthorized"); require(block.timestamp <= deadline, "Tribe: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @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 rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { 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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { 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), "Tribe: invalid signature"); require(nonce == nonces[signatory]++, "Tribe: invalid nonce"); require(block.timestamp <= expiry, "Tribe: 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 (uint96) { 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, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe: 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]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require(src != address(0), "Tribe: cannot transfer from the zero address"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Tribe: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Tribe: 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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint256) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 virtual override returns (address) { return _roleMembers[role].at(index); } /** * @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 virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @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 { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, 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) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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); }
Admin functionality to turn on pod membership transfers Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role
function unlockMembershipTransfers(uint256 _podId) external override hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId)) { _setMembershipTransferLock(_podId, false); }
9,855,914
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import {IDepositZap} from "../../interfaces/curve/IDepositZap.sol"; import {IERC20Detailed} from "../../interfaces/IERC20Detailed.sol"; import {ICurveDeposit_4token} from "../../interfaces/curve/ICurveDeposit_4token.sol"; import {ConvexFactoryMetaPoolStrategy} from "./ConvexFactoryMetaPoolStrategy.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; contract ConvexStrategyMetaBTC is ConvexFactoryMetaPoolStrategy { using SafeERC20 for IERC20Detailed; /// @notice curve N_COINS for the pool uint256 public constant CURVE_UNDERLYINGS_SIZE = 4; /// @notice curve sBTC deposit zap address public constant META_BTC_DEPOSIT_ZAP = address(0x7AbDBAf29929e7F8621B757D2a7c04d78d633834); /// @return size of the curve deposit array function _curveUnderlyingsSize() internal pure override returns (uint256) { return CURVE_UNDERLYINGS_SIZE; } /// @notice Deposits in Curve for metapools based on sbtc function _depositInCurve(uint256 _minLpTokens) internal override { IERC20Detailed _deposit = IERC20Detailed(curveDeposit); uint256 _balance = _deposit.balanceOf(address(this)); address _pool = curveLpToken; _deposit.safeApprove(META_BTC_DEPOSIT_ZAP, 0); _deposit.safeApprove(META_BTC_DEPOSIT_ZAP, _balance); // we can accept 0 as minimum, this will be called only by trusted roles // we also use the zap to deploy funds into a meta pool uint256[4] memory _depositArray; _depositArray[depositPosition] = _balance; IDepositZap(META_BTC_DEPOSIT_ZAP).add_liquidity( _pool, _depositArray, _minLpTokens ); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IDepositZap { /// @notice Wraps underlying coins and deposit them into _pool. /// Returns the amount of LP tokens that were minted in the deposit. function add_liquidity( address _pool, uint256[4] memory _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); function add_liquidity( uint256[4] memory _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IERC20Detailed is IERC20Upgradeable { function name() external view returns(string memory); function symbol() external view returns(string memory); function decimals() external view returns(uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface ICurveDeposit_4token { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import {ConvexBaseStrategy} from "./ConvexBaseStrategy.sol"; import {IMetaPoolRegistry} from "../../interfaces/curve/IMetaPoolRegistry.sol"; abstract contract ConvexFactoryMetaPoolStrategy is ConvexBaseStrategy { /// @notice curve metapool factory address public constant METAPOOL_FACTORY = address(0xB9fC157394Af804a3578134A6585C0dc9cc990d4); /// @dev This method queries the Metapool Factory to get the underlying coins of a /// plain pool created with the factory (no wrapped assets). function _curveUnderlyingCoins(address _curveLpToken, uint256 _position) internal view override returns (address) { address[4] memory _coins = IMetaPoolRegistry(METAPOOL_FACTORY).get_underlying_coins(_curveLpToken); return _coins[_position]; } } // SPDX-License-Identifier: MIT 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' // 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(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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT 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: UNLICENSED pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "../../interfaces/IIdleCDOStrategy.sol"; import "../../interfaces/IERC20Detailed.sol"; import "../../interfaces/convex/IBooster.sol"; import "../../interfaces/convex/IBaseRewardPool.sol"; import "../../interfaces/curve/IMainRegistry.sol"; /// @author @dantop114 /// @title ConvexStrategy /// @notice IIdleCDOStrategy to deploy funds in Convex Finance /// @dev This contract should not have any funds at the end of each tx. /// The contract is upgradable, to add storage slots, add them after the last `###### End of storage VXX` abstract contract ConvexBaseStrategy is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC20Upgradeable, IIdleCDOStrategy { using SafeERC20Upgradeable for IERC20Detailed; /// ###### Storage V1 /// @notice one curve lp token /// @dev we use this as base unit of the strategy token too uint256 public ONE_CURVE_LP_TOKEN; /// @notice convex rewards pool id for the underlying curve lp token uint256 public poolID; /// @notice curve lp token to deposit in convex address public curveLpToken; /// @notice deposit token address to deposit into curve pool address public curveDeposit; /// @notice depositor contract used to deposit underlyings address public depositor; /// @notice deposit token array position uint256 public depositPosition; /// @notice convex crv rewards pool address address public rewardPool; /// @notice decimals of the underlying asset uint256 public curveLpDecimals; /// @notice Curve main registry address public constant MAIN_REGISTRY = address(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5); /// @notice convex booster address address public constant BOOSTER = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); /// @notice weth token address address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice curve ETH mock address address public constant ETH = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /// @notice whitelisted CDO for this strategy address public whitelistedCDO; /// @notice convex rewards for this specific lp token (cvx should be included in this list) address[] public convexRewards; /// @notice WETH to deposit token path address[] public weth2DepositPath; /// @notice univ2 router for weth to deposit swap address public weth2DepositRouter; /// @notice reward liquidation to WETH path mapping(address => address[]) public reward2WethPath; /// @notice univ2-like router for each reward mapping(address => address) public rewardRouter; /// @notice total LP tokens staked uint256 public totalLpTokensStaked; /// @notice total LP tokens locked uint256 public totalLpTokensLocked; /// @notice harvested LP tokens release delay uint256 public releaseBlocksPeriod; /// @notice latest harvest uint256 public latestHarvestBlock; /// ###### End of storage V1 /// ###### Storage V2 /// @notice blocks per year uint256 public BLOCKS_PER_YEAR; /// @notice latest harvest price gain in LP tokens uint256 public latestPriceIncrease; /// @notice latest estimated harvest interval uint256 public latestHarvestInterval; // ################### // Modifiers // ################### modifier onlyWhitelistedCDO() { require(msg.sender == whitelistedCDO, "Not whitelisted CDO"); _; } // Used to prevent initialization of the implementation contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { curveLpToken = address(1); } // ################### // Initializer // ################### // Struct used to set Curve deposits struct CurveArgs { address deposit; address depositor; uint256 depositPosition; } // Struct used to initialize rewards swaps struct Reward { address reward; address router; address[] path; } // Struct used to initialize WETH -> deposit swaps struct Weth2Deposit { address router; address[] path; } /// @notice can only be called once /// @dev Initialize the upgradable contract. If `_deposit` equals WETH address, _weth2Deposit is ignored as param. /// @param _poolID convex pool id /// @param _owner owner address /// @param _curveArgs curve addresses and deposit details /// @param _rewards initial rewards (with paths and routers) /// @param _weth2Deposit initial WETH -> deposit paths and routers function initialize( uint256 _poolID, address _owner, uint256 _releasePeriod, CurveArgs memory _curveArgs, Reward[] memory _rewards, Weth2Deposit memory _weth2Deposit ) public initializer { // Sanity checks require(curveLpToken == address(0), "Initialized"); require(_curveArgs.depositPosition < _curveUnderlyingsSize(), "Deposit token position invalid"); // Initialize contracts OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); // Check Curve LP Token and Convex PoolID (address _crvLp, , , address _rewardPool, , bool shutdown) = IBooster(BOOSTER).poolInfo(_poolID); curveLpToken = _crvLp; // Pool and deposit asset checks address _deposit = _curveArgs.deposit == WETH ? ETH : _curveArgs.deposit; require(!shutdown, "Convex Pool is not active"); require(_deposit == _curveUnderlyingCoins(_crvLp, _curveArgs.depositPosition), "Deposit token invalid"); ERC20Upgradeable.__ERC20_init( string(abi.encodePacked("Idle ", IERC20Detailed(_crvLp).name(), " Convex Strategy")), string(abi.encodePacked("idleCvx", IERC20Detailed(_crvLp).symbol())) ); // Set basic parameters poolID = _poolID; rewardPool = _rewardPool; curveLpDecimals = IERC20Detailed(_crvLp).decimals(); ONE_CURVE_LP_TOKEN = 10**(curveLpDecimals); curveDeposit = _curveArgs.deposit; depositor = _curveArgs.depositor; depositPosition = _curveArgs.depositPosition; releaseBlocksPeriod = _releasePeriod; setBlocksPerYear(2465437); // given that blocks are mined at a 13.15s/block rate // set approval for curveLpToken IERC20Detailed(_crvLp).approve(BOOSTER, type(uint256).max); // set initial rewards for (uint256 i = 0; i < _rewards.length; i++) { addReward(_rewards[i].reward, _rewards[i].router, _rewards[i].path); } if (_curveArgs.deposit != WETH) setWeth2Deposit(_weth2Deposit.router, _weth2Deposit.path); // transfer ownership transferOwnership(_owner); } // ################### // Interface implementation // ################### function strategyToken() external view override returns (address) { return address(this); } function oneToken() external view override returns (uint256) { return ONE_CURVE_LP_TOKEN; } // @notice Underlying token function token() external view override returns (address) { return curveLpToken; } // @notice Underlying token decimals function tokenDecimals() external view override returns (uint256) { return curveLpDecimals; } function decimals() public view override returns (uint8) { return uint8(curveLpDecimals); // should be safe } // ################### // Public methods // ################### /// @dev msg.sender should approve this contract first to spend `_amount` of `token` /// @param _amount amount of `token` to deposit /// @return minted amount of strategy tokens minted function deposit(uint256 _amount) external override onlyWhitelistedCDO returns (uint256 minted) { if (_amount > 0) { /// get `tokens` from msg.sender IERC20Detailed(curveLpToken).safeTransferFrom(msg.sender, address(this), _amount); minted = _depositAndMint(msg.sender, _amount, price()); } } /// @dev msg.sender doesn't need to approve the spending of strategy token /// @param _amount amount of strategyTokens to redeem /// @return redeemed amount of underlyings redeemed function redeem(uint256 _amount) external onlyWhitelistedCDO override returns (uint256 redeemed) { if(_amount > 0) { redeemed = _redeem(msg.sender, _amount, price()); } } /// @dev msg.sender should approve this contract first /// to spend `_amount * ONE_IDLE_TOKEN / price()` of `strategyToken` /// @param _amount amount of underlying tokens to redeem /// @return redeemed amount of underlyings redeemed function redeemUnderlying(uint256 _amount) external override onlyWhitelistedCDO returns (uint256 redeemed) { if (_amount > 0) { uint256 _cachedPrice = price(); uint256 _shares = (_amount * ONE_CURVE_LP_TOKEN) / _cachedPrice; redeemed = _redeem(msg.sender, _shares, _cachedPrice); } } /// @notice Anyone can call this because this contract holds no strategy tokens and so no 'old' rewards /// @dev msg.sender should approve this contract first to spend `_amount` of `strategyToken`. /// redeem rewards and transfer them to msg.sender /// @param _extraData extra data to be used when selling rewards for min amounts /// @return _balances array of minAmounts to use for swapping rewards to WETH, then weth to depositToken, then depositToken to curveLpToken function redeemRewards(bytes calldata _extraData) external override onlyWhitelistedCDO returns (uint256[] memory _balances) { address[] memory _convexRewards = convexRewards; // +2 for converting rewards to depositToken and then Curve LP Token _balances = new uint256[](_convexRewards.length + 2); // decode params from _extraData to get the min amount for each convexRewards uint256[] memory _minAmountsWETH = new uint256[](_convexRewards.length); bool[] memory _skipSell = new bool[](_convexRewards.length); uint256 _minDepositToken; uint256 _minLpToken; (_minAmountsWETH, _skipSell, _minDepositToken, _minLpToken) = abi.decode(_extraData, (uint256[], bool[], uint256, uint256)); IBaseRewardPool(rewardPool).getReward(); address _reward; IERC20Detailed _rewardToken; uint256 _rewardBalance; IUniswapV2Router02 _router; for (uint256 i = 0; i < _convexRewards.length; i++) { if (_skipSell[i]) continue; _reward = _convexRewards[i]; // get reward balance and safety check _rewardToken = IERC20Detailed(_reward); _rewardBalance = _rewardToken.balanceOf(address(this)); if (_rewardBalance == 0) continue; _router = IUniswapV2Router02( rewardRouter[_reward] ); // approve to v2 router _rewardToken.safeApprove(address(_router), 0); _rewardToken.safeApprove(address(_router), _rewardBalance); address[] memory _reward2WethPath = reward2WethPath[_reward]; uint256[] memory _res = new uint256[](_reward2WethPath.length); _res = _router.swapExactTokensForTokens( _rewardBalance, _minAmountsWETH[i], _reward2WethPath, address(this), block.timestamp ); // save in returned value the amount of weth receive to use off-chain _balances[i] = _res[_res.length - 1]; } if (curveDeposit != WETH) { IERC20Detailed _weth = IERC20Detailed(WETH); IUniswapV2Router02 _wethRouter = IUniswapV2Router02( weth2DepositRouter ); uint256 _wethBalance = _weth.balanceOf(address(this)); _weth.safeApprove(address(_wethRouter), 0); _weth.safeApprove(address(_wethRouter), _wethBalance); address[] memory _weth2DepositPath = weth2DepositPath; uint256[] memory _res = new uint256[](_weth2DepositPath.length); _res = _wethRouter.swapExactTokensForTokens( _wethBalance, _minDepositToken, _weth2DepositPath, address(this), block.timestamp ); // save in _balances the amount of depositToken to use off-chain _balances[_convexRewards.length] = _res[_res.length - 1]; } IERC20Detailed _curveLpToken = IERC20Detailed(curveLpToken); uint256 _curveLpBalanceBefore = _curveLpToken.balanceOf(address(this)); _depositInCurve(_minLpToken); uint256 _curveLpBalanceAfter = _curveLpToken.balanceOf(address(this)); uint256 _gainedLpTokens = (_curveLpBalanceAfter - _curveLpBalanceBefore); // save in _balances the amount of curveLpTokens received to use off-chain _balances[_convexRewards.length + 1] = _gainedLpTokens; if (_curveLpBalanceAfter > 0) { // deposit in curve and stake on convex _stakeConvex(_curveLpBalanceAfter); // update locked lp tokens and apr computation variables latestHarvestInterval = (block.number - latestHarvestBlock); latestHarvestBlock = block.number; totalLpTokensLocked = _gainedLpTokens; // inline price increase calculation latestPriceIncrease = (_gainedLpTokens * ONE_CURVE_LP_TOKEN) / totalSupply(); } } // ################### // Views // ################### /// @return _price net price in underlyings of 1 strategyToken function price() public view override returns (uint256 _price) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { _price = ONE_CURVE_LP_TOKEN; } else { _price = ((totalLpTokensStaked - _lockedLpTokens()) * ONE_CURVE_LP_TOKEN) / _totalSupply; } } /// @return returns an APR estimation. /// @dev values returned by this method should be taken as an imprecise estimation. /// For client integration something more complex should be done to have a more precise /// estimate (eg. computing APR using historical APR data). /// Also it does not take into account compounding (APY). function getApr() external view override returns (uint256) { // apr = rate * blocks in a year / harvest interval return latestPriceIncrease * (BLOCKS_PER_YEAR / latestHarvestInterval) * 100; } /// @return rewardTokens tokens array of reward token addresses function getRewardTokens() external view override returns (address[] memory rewardTokens) {} // ################### // Protected // ################### /// @notice Allow the CDO to pull stkAAVE rewards. Anyone can call this /// @return 0, this function is a noop in this strategy function pullStkAAVE() external pure override returns (uint256) { return 0; } /// @notice This contract should not have funds at the end of each tx (except for stkAAVE), this method is just for leftovers /// @dev Emergency method /// @param _token address of the token to transfer /// @param value amount of `_token` to transfer /// @param _to receiver address function transferToken( address _token, uint256 value, address _to ) external onlyOwner nonReentrant { IERC20Detailed(_token).safeTransfer(_to, value); } /// @notice This method can be used to change the value of BLOCKS_PER_YEAR /// @param blocksPerYear the new blocks per year value function setBlocksPerYear(uint256 blocksPerYear) public onlyOwner { require(blocksPerYear != 0, "Blocks per year cannot be zero"); BLOCKS_PER_YEAR = blocksPerYear; } function setRouterForReward(address _reward, address _newRouter) external onlyOwner { require(_newRouter != address(0), "Router is address zero"); rewardRouter[_reward] = _newRouter; } function setPathForReward(address _reward, address[] memory _newPath) external onlyOwner { _validPath(_newPath, WETH); reward2WethPath[_reward] = _newPath; } function setWeth2Deposit(address _router, address[] memory _path) public onlyOwner { address _curveDeposit = curveDeposit; require(_curveDeposit != WETH, "Deposit asset is WETH"); _validPath(_path, _curveDeposit); weth2DepositRouter = _router; weth2DepositPath = _path; } function addReward( address _reward, address _router, address[] memory _path ) public onlyOwner { _validPath(_path, WETH); convexRewards.push(_reward); rewardRouter[_reward] = _router; reward2WethPath[_reward] = _path; } function removeReward(address _reward) external onlyOwner { address[] memory _newConvexRewards = new address[]( convexRewards.length - 1 ); uint256 currentI = 0; for (uint256 i = 0; i < convexRewards.length; i++) { if (convexRewards[i] == _reward) continue; _newConvexRewards[currentI] = convexRewards[i]; currentI += 1; } convexRewards = _newConvexRewards; delete rewardRouter[_reward]; delete reward2WethPath[_reward]; } /// @notice allow to update whitelisted address function setWhitelistedCDO(address _cdo) external onlyOwner { require(_cdo != address(0), "IS_0"); whitelistedCDO = _cdo; } function setReleaseBlocksPeriod(uint256 _period) external onlyOwner { releaseBlocksPeriod = _period; } // ################### // Internal // ################### /// @dev Virtual method to override in specific pool implementation. /// @return number of underlying coins depending on Curve pool function _curveUnderlyingsSize() internal pure virtual returns (uint256); /// @dev Virtual method to override in specific pool implementation. /// This method should implement the deposit in the curve pool. function _depositInCurve(uint256 _minLpTokens) internal virtual; /// @dev Virtual method to override if needed (eg. pool address is equal to lp token address) /// @return address of pool from LP token function _curvePool(address _curveLpToken) internal view virtual returns (address) { return IMainRegistry(MAIN_REGISTRY).get_pool_from_lp_token(_curveLpToken); } /// @dev Virtual method to override if needed (eg. pool is not in the main registry) /// @return address of the nth underlying coin for _curveLpToken function _curveUnderlyingCoins(address _curveLpToken, uint256 _position) internal view virtual returns (address) { address[8] memory _coins = IMainRegistry(MAIN_REGISTRY).get_underlying_coins(_curvePool(_curveLpToken)); return _coins[_position]; } /// @notice Internal helper function to deposit in convex and update total LP tokens staked /// @param _lpTokens number of LP tokens to stake function _stakeConvex(uint256 _lpTokens) internal { // update total staked lp tokens and deposit in convex totalLpTokensStaked += _lpTokens; IBooster(BOOSTER).depositAll(poolID, true); } /// @notice Internal function to deposit in the Convex Booster and mint shares /// @dev Used for deposit and during an harvest /// @param _lpTokens amount to mint /// @param _price we give the price as input to save on gas when calculating price function _depositAndMint( address _account, uint256 _lpTokens, uint256 _price ) internal returns (uint256 minted) { // deposit in convex _stakeConvex(_lpTokens); // mint strategy tokens to msg.sender minted = (_lpTokens * ONE_CURVE_LP_TOKEN) / _price; _mint(_account, minted); } /// @dev msg.sender does not need to approve this contract to spend `_amount` of `strategyToken` /// @param _shares amount of strategyTokens to redeem /// @param _price we give the price as input to save on gas when calculating price /// @return redeemed amount of underlyings redeemed function _redeem( address _account, uint256 _shares, uint256 _price ) internal returns (uint256 redeemed) { // update total staked lp tokens redeemed = (_shares * _price) / ONE_CURVE_LP_TOKEN; totalLpTokensStaked -= redeemed; IERC20Detailed _curveLpToken = IERC20Detailed(curveLpToken); // burn strategy tokens for the msg.sender _burn(_account, _shares); // exit reward pool (without claiming) and unwrap staking position IBaseRewardPool(rewardPool).withdraw(redeemed, false); IBooster(BOOSTER).withdraw(poolID, redeemed); // transfer underlying lp tokens to msg.sender _curveLpToken.safeTransfer(_account, redeemed); } function _lockedLpTokens() internal view returns (uint256 _locked) { uint256 _releaseBlocksPeriod = releaseBlocksPeriod; uint256 _blocksSinceLastHarvest = block.number - latestHarvestBlock; uint256 _totalLockedLpTokens = totalLpTokensLocked; if (_totalLockedLpTokens > 0 && _blocksSinceLastHarvest < _releaseBlocksPeriod) { // progressively release harvested rewards _locked = _totalLockedLpTokens * (_releaseBlocksPeriod - _blocksSinceLastHarvest) / _releaseBlocksPeriod; } } function _validPath(address[] memory _path, address _out) internal pure { require(_path.length >= 2, "Path length less than 2"); require(_path[_path.length - 1] == _out, "Last asset should be WETH"); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IMetaPoolRegistry { function get_coins(address) external view returns (address[4] memory); function get_underlying_coins(address) external view returns(address[4] memory); } // SPDX-License-Identifier: MIT 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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.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 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 * overloaded; * * 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 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"); _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"); _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"); _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: * * - `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 += 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"); _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 { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface IIdleCDOStrategy { function strategyToken() external view returns(address); function token() external view returns(address); function tokenDecimals() external view returns(uint256); function oneToken() external view returns(uint256); function redeemRewards(bytes calldata _extraData) external returns(uint256[] memory); function pullStkAAVE() external returns(uint256); function price() external view returns(uint256); function getRewardTokens() external view returns(address[] memory); function deposit(uint256 _amount) external returns(uint256); // _amount in `strategyToken` function redeem(uint256 _amount) external returns(uint256); // _amount in `token` function redeemUnderlying(uint256 _amount) external returns(uint256); function getApr() external view returns(uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IBooster { function deposit(uint256 _pid, uint256 _amount, bool _stake) external; function depositAll(uint256 _pid, bool _stake) external; function withdraw(uint256 _pid, uint256 _amount) external; function withdrawAll(uint256 _pid) external; function poolInfo(uint256 _pid) external view returns (address lpToken, address, address, address, address, bool); function earmarkRewards(uint256 _pid) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IBaseRewardPool { function balanceOf(address account) external view returns(uint256 amount); function pid() external view returns (uint256 _pid); function stakingToken() external view returns (address _stakingToken); function extraRewardsLength() external view returns (uint256 _length); function rewardToken() external view returns(address _rewardToken); function extraRewards() external view returns(address[] memory _extraRewards); function getReward() external; function stake(uint256 _amount) external; function stakeAll() external; function withdraw(uint256 amount, bool claim) external; function withdrawAll(bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function withdrawAllAndUnwrap(bool claim) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; interface IMainRegistry { function get_pool_from_lp_token(address lp_token) external view returns (address); function get_underlying_coins(address pool) external view returns (address[8] memory); } // 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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 {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 || !_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; /** * @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; // solhint-disable-next-line no-inline-assembly 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"); // 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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
Anyone can call this because this contract holds no strategy tokens and so no 'old' rewards msg.sender should approve this contract first to spend `_amount` of `strategyToken`. redeem rewards and transfer them to msg.sender _extraData extra data to be used when selling rewards for min amounts return _balances array of minAmounts to use for swapping rewards to WETH, then weth to depositToken, then depositToken to curveLpToken +2 for converting rewards to depositToken and then Curve LP Token decode params from _extraData to get the min amount for each convexRewards get reward balance and safety check approve to v2 router save in returned value the amount of weth receive to use off-chain save in _balances the amount of depositToken to use off-chain deposit in curve and stake on convex update locked lp tokens and apr computation variables inline price increase calculation
function redeemRewards(bytes calldata _extraData) external override onlyWhitelistedCDO returns (uint256[] memory _balances) { address[] memory _convexRewards = convexRewards; _balances = new uint256[](_convexRewards.length + 2); uint256[] memory _minAmountsWETH = new uint256[](_convexRewards.length); bool[] memory _skipSell = new bool[](_convexRewards.length); uint256 _minDepositToken; uint256 _minLpToken; (_minAmountsWETH, _skipSell, _minDepositToken, _minLpToken) = abi.decode(_extraData, (uint256[], bool[], uint256, uint256)); IBaseRewardPool(rewardPool).getReward(); address _reward; IERC20Detailed _rewardToken; uint256 _rewardBalance; IUniswapV2Router02 _router; for (uint256 i = 0; i < _convexRewards.length; i++) { if (_skipSell[i]) continue; _reward = _convexRewards[i]; _rewardToken = IERC20Detailed(_reward); _rewardBalance = _rewardToken.balanceOf(address(this)); if (_rewardBalance == 0) continue; _router = IUniswapV2Router02( rewardRouter[_reward] ); _rewardToken.safeApprove(address(_router), 0); _rewardToken.safeApprove(address(_router), _rewardBalance); address[] memory _reward2WethPath = reward2WethPath[_reward]; uint256[] memory _res = new uint256[](_reward2WethPath.length); _res = _router.swapExactTokensForTokens( _rewardBalance, _minAmountsWETH[i], _reward2WethPath, address(this), block.timestamp ); _balances[i] = _res[_res.length - 1]; } if (curveDeposit != WETH) { IERC20Detailed _weth = IERC20Detailed(WETH); IUniswapV2Router02 _wethRouter = IUniswapV2Router02( weth2DepositRouter ); uint256 _wethBalance = _weth.balanceOf(address(this)); _weth.safeApprove(address(_wethRouter), 0); _weth.safeApprove(address(_wethRouter), _wethBalance); address[] memory _weth2DepositPath = weth2DepositPath; uint256[] memory _res = new uint256[](_weth2DepositPath.length); _res = _wethRouter.swapExactTokensForTokens( _wethBalance, _minDepositToken, _weth2DepositPath, address(this), block.timestamp ); _balances[_convexRewards.length] = _res[_res.length - 1]; } IERC20Detailed _curveLpToken = IERC20Detailed(curveLpToken); uint256 _curveLpBalanceBefore = _curveLpToken.balanceOf(address(this)); _depositInCurve(_minLpToken); uint256 _curveLpBalanceAfter = _curveLpToken.balanceOf(address(this)); uint256 _gainedLpTokens = (_curveLpBalanceAfter - _curveLpBalanceBefore); if (_curveLpBalanceAfter > 0) { _stakeConvex(_curveLpBalanceAfter); latestHarvestInterval = (block.number - latestHarvestBlock); latestHarvestBlock = block.number; totalLpTokensLocked = _gainedLpTokens; latestPriceIncrease = (_gainedLpTokens * ONE_CURVE_LP_TOKEN) / totalSupply(); } }
532,854
./full_match/137/0x5c5b7F4cf057484C2f72e929748029D2DE590FcF/sources/nftgrannies.sol
Sends all funds to contract owner
function withdraw() public onlyOwner { require(address(this).balance > 0, "Error: Balance is 0"); payable(owner()).transfer(address(this).balance); }
4,712,534
pragma solidity ^0.4.24; contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. 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 */ constructor(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` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @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.safeTransfer(_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 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 */ constructor(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 PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } 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; } } 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; } } 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 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 ); } 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)); } } contract Oraclized is Ownable { address public oracle; constructor(address _oracle) public { oracle = _oracle; } /** * @dev Change oracle address * @param _oracle Oracle address */ function setOracle(address _oracle) public onlyOwner { oracle = _oracle; } /** * @dev Modifier to allow access only by oracle */ modifier onlyOracle() { require(msg.sender == oracle); _; } /** * @dev Modifier to allow access only by oracle or owner */ modifier onlyOwnerOrOracle() { require((msg.sender == oracle) || (msg.sender == owner)); _; } } contract KYCCrowdsale is Oraclized, PostDeliveryCrowdsale { using SafeMath for uint256; /** * @dev etherPriceInUsd Ether price in cents * @dev usdRaised Total USD raised while ICO in cents * @dev weiInvested Stores amount of wei invested by each user * @dev usdInvested Stores amount of USD invested by each user in cents */ uint256 public etherPriceInUsd; uint256 public usdRaised; mapping (address => uint256) public weiInvested; mapping (address => uint256) public usdInvested; /** * @dev KYCPassed Registry of users who passed KYC * @dev KYCRequired Registry of users who has to passed KYC */ mapping (address => bool) public KYCPassed; mapping (address => bool) public KYCRequired; /** * @dev KYCRequiredAmountInUsd Amount in cents invested starting from which user must pass KYC */ uint256 public KYCRequiredAmountInUsd; event EtherPriceUpdated(uint256 _cents); /** * @param _kycAmountInUsd Amount in cents invested starting from which user must pass KYC */ constructor(uint256 _kycAmountInUsd, uint256 _etherPrice) public { require(_etherPrice > 0); KYCRequiredAmountInUsd = _kycAmountInUsd; etherPriceInUsd = _etherPrice; } /** * @dev Update amount required to pass KYC * @param _cents Amount in cents invested starting from which user must pass KYC */ function setKYCRequiredAmount(uint256 _cents) external onlyOwnerOrOracle { require(_cents > 0); KYCRequiredAmountInUsd = _cents; } /** * @dev Set ether conversion rate * @param _cents Price of 1 ETH in cents */ function setEtherPrice(uint256 _cents) public onlyOwnerOrOracle { require(_cents > 0); etherPriceInUsd = _cents; emit EtherPriceUpdated(_cents); } /** * @dev Check if KYC is required for address * @param _address Address to check */ function isKYCRequired(address _address) external view returns(bool) { return KYCRequired[_address]; } /** * @dev Check if KYC is passed by address * @param _address Address to check */ function isKYCPassed(address _address) external view returns(bool) { return KYCPassed[_address]; } /** * @dev Check if KYC is not required or passed * @param _address Address to check */ function isKYCSatisfied(address _address) public view returns(bool) { return !KYCRequired[_address] || KYCPassed[_address]; } /** * @dev Returns wei invested by specific amount * @param _account Account you would like to get wei for */ function weiInvestedOf(address _account) external view returns (uint256) { return weiInvested[_account]; } /** * @dev Returns cents invested by specific amount * @param _account Account you would like to get cents for */ function usdInvestedOf(address _account) external view returns (uint256) { return usdInvested[_account]; } /** * @dev Update KYC status for set of addresses * @param _addresses Addresses to update * @param _completed Is KYC passed or not */ function updateKYCStatus(address[] _addresses, bool _completed) public onlyOwnerOrOracle { for (uint16 index = 0; index < _addresses.length; index++) { KYCPassed[_addresses[index]] = _completed; } } /** * @dev Override update purchasing state * - update sum of funds invested * - if total amount invested higher than KYC amount set KYC required to true */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); uint256 usdAmount = _weiToUsd(_weiAmount); usdRaised = usdRaised.add(usdAmount); usdInvested[_beneficiary] = usdInvested[_beneficiary].add(usdAmount); weiInvested[_beneficiary] = weiInvested[_beneficiary].add(_weiAmount); if (usdInvested[_beneficiary] >= KYCRequiredAmountInUsd) { KYCRequired[_beneficiary] = true; } } /** * @dev Override token withdraw * - do not allow token withdraw in case KYC required but not passed */ function withdrawTokens() public { require(isKYCSatisfied(msg.sender)); super.withdrawTokens(); } /** * @dev Converts wei to cents * @param _wei Wei amount */ function _weiToUsd(uint256 _wei) internal view returns (uint256) { return _wei.mul(etherPriceInUsd).div(1e18); } /** * @dev Converts cents to wei * @param _cents Cents amount */ function _usdToWei(uint256 _cents) internal view returns (uint256) { return _cents.mul(1e18).div(etherPriceInUsd); } } contract KYCRefundableCrowdsale is KYCCrowdsale { using SafeMath for uint256; /** * @dev percentage multiplier to present percentage as decimals. 5 decimal by default * @dev weiOnFinalize ether balance which was on finalize & will be returned to users in case of failed crowdsale */ uint256 private percentage = 100 * 1000; uint256 private weiOnFinalize; /** * @dev goalReached specifies if crowdsale goal is reached * @dev isFinalized is crowdsale finished * @dev tokensWithdrawn total amount of tokens already withdrawn */ bool public goalReached = false; bool public isFinalized = false; uint256 public tokensWithdrawn; event Refund(address indexed _account, uint256 _amountInvested, uint256 _amountRefunded); event Finalized(); event OwnerWithdraw(uint256 _amount); /** * @dev Set is goal reached or not * @param _success Is goal reached or not */ function setGoalReached(bool _success) external onlyOwner { require(!isFinalized); goalReached = _success; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached); uint256 refundPercentage = _refundPercentage(); uint256 amountInvested = weiInvested[msg.sender]; uint256 amountRefunded = amountInvested.mul(refundPercentage).div(percentage); weiInvested[msg.sender] = 0; usdInvested[msg.sender] = 0; msg.sender.transfer(amountRefunded); emit Refund(msg.sender, amountInvested, amountRefunded); } /** * @dev Must be called after crowdsale ends, to do some extra finalization works. */ function finalize() public onlyOwner { require(!isFinalized); // NOTE: We do this because we would like to allow withdrawals earlier than closing time in case of crowdsale success closingTime = block.timestamp; weiOnFinalize = address(this).balance; isFinalized = true; emit Finalized(); } /** * @dev Override. Withdraw tokens only after crowdsale ends. * Make sure crowdsale is successful & finalized */ function withdrawTokens() public { require(isFinalized); require(goalReached); tokensWithdrawn = tokensWithdrawn.add(balances[msg.sender]); super.withdrawTokens(); } /** * @dev Is called by owner to send funds to ICO wallet. * params _amount Amount to be sent. */ function ownerWithdraw(uint256 _amount) external onlyOwner { require(_amount > 0); wallet.transfer(_amount); emit OwnerWithdraw(_amount); } /** * @dev Override. Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { // NOTE: Do nothing here. Keep funds in contract by default } /** * @dev Calculates refund percentage in case some funds will be used by dev team on crowdsale needs */ function _refundPercentage() internal view returns (uint256) { return weiOnFinalize.mul(percentage).div(weiRaised); } } contract AerumCrowdsale is KYCRefundableCrowdsale { using SafeMath for uint256; /** * @dev minInvestmentInUsd Minimal investment allowed in cents */ uint256 public minInvestmentInUsd; /** * @dev tokensSold Amount of tokens sold by this time */ uint256 public tokensSold; /** * @dev pledgeTotal Total pledge collected from all investors * @dev pledgeClosingTime Time when pledge is closed & it's not possible to pledge more or use pledge more * @dev pledges Mapping of all pledges done by investors */ uint256 public pledgeTotal; uint256 public pledgeClosingTime; mapping (address => uint256) public pledges; /** * @dev whitelistedRate Rate which is used while whitelisted sale (XRM to ETH) * @dev publicRate Rate which is used white public crowdsale (XRM to ETH) */ uint256 public whitelistedRate; uint256 public publicRate; event AirDrop(address indexed _account, uint256 _amount); event MinInvestmentUpdated(uint256 _cents); event RateUpdated(uint256 _whitelistedRate, uint256 _publicRate); event Withdraw(address indexed _account, uint256 _amount); /** * @param _token ERC20 compatible token on which crowdsale is done * @param _wallet Address where all ETH funded will be sent after ICO finishes * @param _whitelistedRate Rate which is used while whitelisted sale * @param _publicRate Rate which is used white public crowdsale * @param _openingTime Crowdsale open time * @param _closingTime Crowdsale close time * @param _pledgeClosingTime Time when pledge is closed & no more active \\ * @param _kycAmountInUsd Amount on which KYC will be required in cents * @param _etherPriceInUsd ETH price in cents */ constructor( ERC20 _token, address _wallet, uint256 _whitelistedRate, uint256 _publicRate, uint256 _openingTime, uint256 _closingTime, uint256 _pledgeClosingTime, uint256 _kycAmountInUsd, uint256 _etherPriceInUsd) Oraclized(msg.sender) Crowdsale(_whitelistedRate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) KYCCrowdsale(_kycAmountInUsd, _etherPriceInUsd) KYCRefundableCrowdsale() public { require(_openingTime < _pledgeClosingTime && _pledgeClosingTime < _closingTime); pledgeClosingTime = _pledgeClosingTime; whitelistedRate = _whitelistedRate; publicRate = _publicRate; minInvestmentInUsd = 25 * 100; } /** * @dev Update minimal allowed investment */ function setMinInvestment(uint256 _cents) external onlyOwnerOrOracle { minInvestmentInUsd = _cents; emit MinInvestmentUpdated(_cents); } /** * @dev Update closing time * @param _closingTime Closing time */ function setClosingTime(uint256 _closingTime) external onlyOwner { require(_closingTime >= openingTime); closingTime = _closingTime; } /** * @dev Update pledge closing time * @param _pledgeClosingTime Pledge closing time */ function setPledgeClosingTime(uint256 _pledgeClosingTime) external onlyOwner { require(_pledgeClosingTime >= openingTime && _pledgeClosingTime <= closingTime); pledgeClosingTime = _pledgeClosingTime; } /** * @dev Update rates * @param _whitelistedRate Rate which is used while whitelisted sale (XRM to ETH) * @param _publicRate Rate which is used white public crowdsale (XRM to ETH) */ function setRate(uint256 _whitelistedRate, uint256 _publicRate) public onlyOwnerOrOracle { require(_whitelistedRate > 0); require(_publicRate > 0); whitelistedRate = _whitelistedRate; publicRate = _publicRate; emit RateUpdated(_whitelistedRate, _publicRate); } /** * @dev Update rates & ether price. Done to not make 2 requests from oracle. * @param _whitelistedRate Rate which is used while whitelisted sale * @param _publicRate Rate which is used white public crowdsale * @param _cents Price of 1 ETH in cents */ function setRateAndEtherPrice(uint256 _whitelistedRate, uint256 _publicRate, uint256 _cents) external onlyOwnerOrOracle { setRate(_whitelistedRate, _publicRate); setEtherPrice(_cents); } /** * @dev Send remaining tokens back * @param _to Address to send * @param _amount Amount to send */ function sendTokens(address _to, uint256 _amount) external onlyOwner { if (!isFinalized || goalReached) { // NOTE: if crowdsale not finished or successful we should keep at least tokens sold _ensureTokensAvailable(_amount); } token.transfer(_to, _amount); } /** * @dev Get balance fo tokens bought * @param _address Address of investor */ function balanceOf(address _address) external view returns (uint256) { return balances[_address]; } /** * @dev Check if all tokens were sold */ function capReached() public view returns (bool) { return tokensSold >= token.balanceOf(this); } /** * @dev Returns percentage of tokens sold */ function completionPercentage() external view returns (uint256) { uint256 balance = token.balanceOf(this); if (balance == 0) { return 0; } return tokensSold.mul(100).div(balance); } /** * @dev Returns remaining tokens based on stage */ function tokensRemaining() external view returns(uint256) { return token.balanceOf(this).sub(_tokensLocked()); } /** * @dev Override. Withdraw tokens only after crowdsale ends. * Adding withdraw event */ function withdrawTokens() public { uint256 amount = balances[msg.sender]; super.withdrawTokens(); emit Withdraw(msg.sender, amount); } /** * @dev Override crowdsale pre validate. Check: * - is amount invested larger than minimal * - there is enough tokens on balance of contract to proceed * - check if pledges amount are not more than total coins (in case of pledge period) */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(_totalInvestmentInUsd(_beneficiary, _weiAmount) >= minInvestmentInUsd); _ensureTokensAvailableExcludingPledge(_beneficiary, _getTokenAmount(_weiAmount)); } /** * @dev Returns total investment of beneficiary including current one in cents * @param _beneficiary Address to check * @param _weiAmount Current amount being invested in wei */ function _totalInvestmentInUsd(address _beneficiary, uint256 _weiAmount) internal view returns(uint256) { return usdInvested[_beneficiary].add(_weiToUsd(_weiAmount)); } /** * @dev Override process purchase * - additionally sum tokens sold */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { super._processPurchase(_beneficiary, _tokenAmount); tokensSold = tokensSold.add(_tokenAmount); if (pledgeOpen()) { // NOTE: In case of buying tokens inside pledge it doesn't matter how we decrease pledge as we change it anyway _decreasePledge(_beneficiary, _tokenAmount); } } /** * @dev Decrease pledge of account by specific token amount * @param _beneficiary Account to increase pledge * @param _tokenAmount Amount of tokens to decrease pledge */ function _decreasePledge(address _beneficiary, uint256 _tokenAmount) internal { if (pledgeOf(_beneficiary) <= _tokenAmount) { pledgeTotal = pledgeTotal.sub(pledgeOf(_beneficiary)); pledges[_beneficiary] = 0; } else { pledgeTotal = pledgeTotal.sub(_tokenAmount); pledges[_beneficiary] = pledges[_beneficiary].sub(_tokenAmount); } } /** * @dev Override to use whitelisted or public crowdsale rates */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return _weiAmount.mul(currentRate); } /** * @dev Returns current XRM to ETH rate based on stage */ function getCurrentRate() public view returns (uint256) { if (pledgeOpen()) { return whitelistedRate; } return publicRate; } /** * @dev Check if pledge period is still open */ function pledgeOpen() public view returns (bool) { return (openingTime <= block.timestamp) && (block.timestamp <= pledgeClosingTime); } /** * @dev Returns amount of pledge for account */ function pledgeOf(address _address) public view returns (uint256) { return pledges[_address]; } /** * @dev Check if all tokens were pledged */ function pledgeCapReached() public view returns (bool) { return pledgeTotal.add(tokensSold) >= token.balanceOf(this); } /** * @dev Returns percentage of tokens pledged */ function pledgeCompletionPercentage() external view returns (uint256) { uint256 balance = token.balanceOf(this); if (balance == 0) { return 0; } return pledgeTotal.add(tokensSold).mul(100).div(balance); } /** * @dev Pledges * @param _addresses list of addresses * @param _tokens List of tokens to drop */ function pledge(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle { require(_addresses.length == _tokens.length); _ensureTokensListAvailable(_tokens); for (uint16 index = 0; index < _addresses.length; index++) { pledgeTotal = pledgeTotal.sub(pledges[_addresses[index]]).add(_tokens[index]); pledges[_addresses[index]] = _tokens[index]; } } /** * @dev Air drops tokens to users * @param _addresses list of addresses * @param _tokens List of tokens to drop */ function airDropTokens(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle { require(_addresses.length == _tokens.length); _ensureTokensListAvailable(_tokens); for (uint16 index = 0; index < _addresses.length; index++) { tokensSold = tokensSold.add(_tokens[index]); balances[_addresses[index]] = balances[_addresses[index]].add(_tokens[index]); emit AirDrop(_addresses[index], _tokens[index]); } } /** * @dev Ensure token list total is available * @param _tokens list of tokens amount */ function _ensureTokensListAvailable(uint256[] _tokens) internal { uint256 total; for (uint16 index = 0; index < _tokens.length; index++) { total = total.add(_tokens[index]); } _ensureTokensAvailable(total); } /** * @dev Ensure amount of tokens you would like to buy or pledge is available * @param _tokens Amount of tokens to buy or pledge */ function _ensureTokensAvailable(uint256 _tokens) internal view { require(_tokens.add(_tokensLocked()) <= token.balanceOf(this)); } /** * @dev Ensure amount of tokens you would like to buy or pledge is available excluding pledged for account * @param _account Account which is checked for pledge * @param _tokens Amount of tokens to buy or pledge */ function _ensureTokensAvailableExcludingPledge(address _account, uint256 _tokens) internal view { require(_tokens.add(_tokensLockedExcludingPledge(_account)) <= token.balanceOf(this)); } /** * @dev Returns locked or sold tokens based on stage */ function _tokensLocked() internal view returns(uint256) { uint256 locked = tokensSold.sub(tokensWithdrawn); if (pledgeOpen()) { locked = locked.add(pledgeTotal); } return locked; } /** * @dev Returns locked or sold tokens based on stage excluding pledged for account * @param _account Account which is checked for pledge */ function _tokensLockedExcludingPledge(address _account) internal view returns(uint256) { uint256 locked = _tokensLocked(); if (pledgeOpen()) { locked = locked.sub(pledgeOf(_account)); } return locked; } }
Pledges _addresses list of addresses _tokens List of tokens to drop/
function pledge(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle { require(_addresses.length == _tokens.length); _ensureTokensListAvailable(_tokens); for (uint16 index = 0; index < _addresses.length; index++) { pledgeTotal = pledgeTotal.sub(pledges[_addresses[index]]).add(_tokens[index]); pledges[_addresses[index]] = _tokens[index]; } }
889,616
pragma solidity ^0.4.23; import "./CompliantToken.sol"; import "./TrueCoinReceiver.sol"; contract CompliantDepositTokenWithHook is CompliantToken { bytes32 constant IS_REGISTERED_CONTRACT = "isRegisteredContract"; bytes32 constant IS_DEPOSIT_ADDRESS = "isDepositAddress"; uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000; /** * @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) { address _from = msg.sender; if (uint256(_to) < REDEMPTION_ADDRESS_COUNT) { registry.requireCanTransfer(_from, _to); _value -= _value % CENT; _burnFromAllArgs(_from, _to, _value); } else { _transferAllArgs(_from, _to, _value); } return true; } /** * @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) { if (uint256(_to) < REDEMPTION_ADDRESS_COUNT) { registry.requireCanTransferFrom(msg.sender, _from, _to); _value -= _value % CENT; allowances.subAllowance(_from, msg.sender, _value); _burnFromAllArgs(_from, _to, _value); } else { _transferFromAllArgs(_from, _to, _value, msg.sender); } return true; } function _burnFromAllArgs(address _from, address _to, uint256 _value) internal { registry.requireCanBurn(_to); require(_value >= burnMin, "below min burn bound"); require(_value <= burnMax, "exceeds max burn bound"); balances.subBalance(_from, _value); emit Transfer(_from, _to, _value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_to, _value); emit Transfer(_to, address(0), _value); } function _transferFromAllArgs(address _from, address _to, uint256 _value, address _sender) internal { bool hasHook; address originalTo = _to; (_to, hasHook) = registry.requireCanTransferFrom(_sender, _from, _to); allowances.subAllowance(_from, _sender, _value); balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, originalTo, _value); if (originalTo != _to) { emit Transfer(originalTo, _to, _value); if (hasHook) { TrueCoinReceiver(_to).tokenFallback(originalTo, _value); } } else { if (hasHook) { TrueCoinReceiver(_to).tokenFallback(_from, _value); } } } function _transferAllArgs(address _from, address _to, uint256 _value) internal { bool hasHook; address originalTo = _to; (_to, hasHook) = registry.requireCanTransfer(_from, _to); balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, originalTo, _value); if (originalTo != _to) { emit Transfer(originalTo, _to, _value); if (hasHook) { TrueCoinReceiver(_to).tokenFallback(originalTo, _value); } } else { if (hasHook) { TrueCoinReceiver(_to).tokenFallback(_from, _value); } } } function mint(address _to, uint256 _value) public onlyOwner { require(_to != address(0), "to address cannot be zero"); bool hasHook; address originalTo = _to; (_to, hasHook) = registry.requireCanMint(_to); totalSupply_ = totalSupply_.add(_value); emit Mint(originalTo, _value); emit Transfer(address(0), originalTo, _value); if (_to != originalTo) { emit Transfer(originalTo, _to, _value); } balances.addBalance(_to, _value); if (hasHook) { if (_to != originalTo) { TrueCoinReceiver(_to).tokenFallback(originalTo, _value); } else { TrueCoinReceiver(_to).tokenFallback(address(0), _value); } } } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { address _from = msg.sender; if (uint256(_to) < REDEMPTION_ADDRESS_COUNT) { registry.requireCanTransfer(_from, _to); _value -= _value % CENT; _burnFromAllArgs(_from, _to, _value); _transferAllArgs(_from, _to, _value); } return true; }
15,836,333
/// GebLenderFirstResortRewardsVested.sol // Copyright (C) 2021 Reflexer Labs, INC // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.7; /** * @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 () internal { _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; } } abstract contract TokenLike { function decimals() virtual public view returns (uint8); function totalSupply() virtual public view returns (uint256); function balanceOf(address) virtual public view returns (uint256); function mint(address, uint) virtual public; function burn(address, uint) virtual public; function approve(address, uint256) virtual external returns (bool); function transfer(address, uint256) virtual external returns (bool); function transferFrom(address,address,uint256) virtual external returns (bool); } abstract contract AuctionHouseLike { function activeStakedTokenAuctions() virtual public view returns (uint256); function startAuction(uint256, uint256) virtual external returns (uint256); } abstract contract AccountingEngineLike { function debtAuctionBidSize() virtual public view returns (uint256); function unqueuedUnauctionedDebt() virtual public view returns (uint256); } abstract contract SAFEEngineLike { function coinBalance(address) virtual public view returns (uint256); function debtBalance(address) virtual public view returns (uint256); } abstract contract RewardDripperLike { function dripReward() virtual external; function dripReward(address) virtual external; function rewardPerBlock() virtual external view returns (uint256); function rewardToken() virtual external view returns (TokenLike); } abstract contract StakingRewardsEscrowLike { function escrowRewards(address, uint256) virtual external; } // Stores tokens, owned by GebLenderFirstResortRewardsVested contract TokenPool { TokenLike public token; address public owner; constructor(address token_) public { token = TokenLike(token_); owner = msg.sender; } // @notice Transfers tokens from the pool (callable by owner only) function transfer(address to, uint256 wad) public { require(msg.sender == owner, "unauthorized"); require(token.transfer(to, wad), "TokenPool/failed-transfer"); } // @notice Returns token balance of the pool function balance() public view returns (uint256) { return token.balanceOf(address(this)); } } contract GebLenderFirstResortRewardsVested is ReentrancyGuard { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "GebLenderFirstResortRewardsVested/account-not-authorized"); _; } // --- Structs --- struct ExitRequest { // Exit window deadline uint256 deadline; // Ancestor amount queued for exit uint256 lockedAmount; } // --- Variables --- // Flag that allows/blocks joining bool public canJoin; // Flag that indicates whether canPrintProtocolTokens can ignore auctioning ancestor tokens bool public bypassAuctions; // Whether the contract allows forced exits or not bool public forcedExit; // Last block when a reward was pulled uint256 public lastRewardBlock; // The current delay enforced on an exit uint256 public exitDelay; // Min maount of ancestor tokens that must remain in the contract and not be auctioned uint256 public minStakedTokensToKeep; // Max number of auctions that can be active at a time uint256 public maxConcurrentAuctions; // Amount of ancestor tokens to auction at a time uint256 public tokensToAuction; // Initial amount of system coins to request in exchange for tokensToAuction uint256 public systemCoinsToRequest; // Amount of rewards per share accumulated (total, see rewardDebt for more info) uint256 public accTokensPerShare; // Balance of the rewards token in this contract since last update uint256 public rewardsBalance; // Staked Supply (== sum of all staked balances) uint256 public stakedSupply; // Percentage of claimed rewards that will be vested uint256 public percentageVested; // Whether the escrow is paused or not uint256 public escrowPaused; // Balances (not affected by slashing) mapping(address => uint256) public descendantBalanceOf; // Exit data mapping(address => ExitRequest) public exitRequests; // The amount of tokens inneligible for claiming rewards (see formula below) mapping(address => uint256) internal rewardDebt; // Pending reward = (descendant.balanceOf(user) * accTokensPerShare) - rewardDebt[user] // The token being deposited in the pool TokenPool public ancestorPool; // The token used to pay rewards TokenPool public rewardPool; // Descendant token TokenLike public descendant; // Auction house for staked tokens AuctionHouseLike public auctionHouse; // Accounting engine contract AccountingEngineLike public accountingEngine; // The safe engine contract SAFEEngineLike public safeEngine; // Contract that drips rewards RewardDripperLike public rewardDripper; // Escrow for rewards StakingRewardsEscrowLike public escrow; // Max delay that can be enforced for an exit uint256 public immutable MAX_DELAY; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 indexed parameter, uint256 data); event ModifyParameters(bytes32 indexed parameter, address data); event ToggleJoin(bool canJoin); event ToggleBypassAuctions(bool bypassAuctions); event ToggleForcedExit(bool forcedExit); event AuctionAncestorTokens(address auctionHouse, uint256 amountAuctioned, uint256 amountRequested); event RequestExit(address indexed account, uint256 deadline, uint256 amount); event Join(address indexed account, uint256 price, uint256 amount); event Exit(address indexed account, uint256 price, uint256 amount); event RewardsPaid(address account, uint256 amount); event EscrowRewards(address escrow, address who, uint256 amount); event PoolUpdated(uint256 accTokensPerShare, uint256 stakedSupply); event FailEscrowRewards(bytes revertReason); constructor( address ancestor_, address descendant_, address rewardToken_, address auctionHouse_, address accountingEngine_, address safeEngine_, address rewardDripper_, address escrow_, uint256 maxDelay_, uint256 exitDelay_, uint256 minStakedTokensToKeep_, uint256 tokensToAuction_, uint256 systemCoinsToRequest_, uint256 percentageVested_ ) public { require(maxDelay_ > 0, "GebLenderFirstResortRewardsVested/null-max-delay"); require(exitDelay_ <= maxDelay_, "GebLenderFirstResortRewardsVested/invalid-exit-delay"); require(minStakedTokensToKeep_ > 0, "GebLenderFirstResortRewardsVested/null-min-staked-tokens"); require(tokensToAuction_ > 0, "GebLenderFirstResortRewardsVested/null-tokens-to-auction"); require(systemCoinsToRequest_ > 0, "GebLenderFirstResortRewardsVested/null-sys-coins-to-request"); require(auctionHouse_ != address(0), "GebLenderFirstResortRewardsVested/null-auction-house"); require(accountingEngine_ != address(0), "GebLenderFirstResortRewardsVested/null-accounting-engine"); require(safeEngine_ != address(0), "GebLenderFirstResortRewardsVested/null-safe-engine"); require(rewardDripper_ != address(0), "GebLenderFirstResortRewardsVested/null-reward-dripper"); require(escrow_ != address(0), "GebLenderFirstResortRewardsVested/null-escrow"); require(percentageVested_ < 100, "GebLenderFirstResortRewardsVested/invalid-percentage-vested"); require(descendant_ != address(0), "GebLenderFirstResortRewardsVested/null-descendant"); authorizedAccounts[msg.sender] = 1; canJoin = true; maxConcurrentAuctions = uint(-1); MAX_DELAY = maxDelay_; exitDelay = exitDelay_; minStakedTokensToKeep = minStakedTokensToKeep_; tokensToAuction = tokensToAuction_; systemCoinsToRequest = systemCoinsToRequest_; percentageVested = percentageVested_; auctionHouse = AuctionHouseLike(auctionHouse_); accountingEngine = AccountingEngineLike(accountingEngine_); safeEngine = SAFEEngineLike(safeEngine_); rewardDripper = RewardDripperLike(rewardDripper_); escrow = StakingRewardsEscrowLike(escrow_); descendant = TokenLike(descendant_); ancestorPool = new TokenPool(ancestor_); rewardPool = new TokenPool(rewardToken_); lastRewardBlock = block.number; require(ancestorPool.token().decimals() == 18, "GebLenderFirstResortRewardsVested/ancestor-decimal-mismatch"); require(descendant.decimals() == 18, "GebLenderFirstResortRewardsVested/descendant-decimal-mismatch"); emit AddAuthorization(msg.sender); } // --- Boolean Logic --- function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Math --- uint256 public constant WAD = 10 ** 18; uint256 public constant RAY = 10 ** 27; function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "GebLenderFirstResortRewardsVested/add-overflow"); } function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "GebLenderFirstResortRewardsVested/sub-underflow"); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "GebLenderFirstResortRewardsVested/mul-overflow"); } function wdivide(uint x, uint y) internal pure returns (uint z) { require(y > 0, "GebLenderFirstResortRewardsVested/wdiv-by-zero"); z = multiply(x, WAD) / y; } function wmultiply(uint x, uint y) internal pure returns (uint z) { z = multiply(x, y) / WAD; } // --- Administration --- /* * @notify Switch between allowing and disallowing joins */ function toggleJoin() external isAuthorized { canJoin = !canJoin; emit ToggleJoin(canJoin); } /* * @notify Switch between ignoring and taking into account auctions in canPrintProtocolTokens */ function toggleBypassAuctions() external isAuthorized { bypassAuctions = !bypassAuctions; emit ToggleBypassAuctions(bypassAuctions); } /* * @notify Switch between allowing exits when the system is underwater or blocking them */ function toggleForcedExit() external isAuthorized { forcedExit = !forcedExit; emit ToggleForcedExit(forcedExit); } /* * @notify Modify an uint256 parameter * @param parameter The name of the parameter to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "exitDelay") { require(data <= MAX_DELAY, "GebLenderFirstResortRewardsVested/invalid-exit-delay"); exitDelay = data; } else if (parameter == "minStakedTokensToKeep") { require(data > 0, "GebLenderFirstResortRewardsVested/null-min-staked-tokens"); minStakedTokensToKeep = data; } else if (parameter == "tokensToAuction") { require(data > 0, "GebLenderFirstResortRewardsVested/invalid-tokens-to-auction"); tokensToAuction = data; } else if (parameter == "systemCoinsToRequest") { require(data > 0, "GebLenderFirstResortRewardsVested/invalid-sys-coins-to-request"); systemCoinsToRequest = data; } else if (parameter == "maxConcurrentAuctions") { require(data > 1, "GebLenderFirstResortRewardsVested/invalid-max-concurrent-auctions"); maxConcurrentAuctions = data; } else if (parameter == "escrowPaused") { require(data <= 1, "GebLenderFirstResortRewardsVested/invalid-escrow-paused"); escrowPaused = data; } else if (parameter == "percentageVested") { require(data < 100, "GebLenderFirstResortRewardsVested/invalid-percentage-vested"); percentageVested = data; } else revert("GebLenderFirstResortRewardsVested/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /* * @notify Modify an address parameter * @param parameter The name of the parameter to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "GebLenderFirstResortRewardsVested/null-data"); if (parameter == "auctionHouse") { auctionHouse = AuctionHouseLike(data); } else if (parameter == "accountingEngine") { accountingEngine = AccountingEngineLike(data); } else if (parameter == "rewardDripper") { rewardDripper = RewardDripperLike(data); } else if (parameter == "escrow") { escrow = StakingRewardsEscrowLike(data); } else revert("GebLenderFirstResortRewardsVested/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Getters --- /* * @notify Return the ancestor token balance for this contract */ function depositedAncestor() public view returns (uint256) { return ancestorPool.balance(); } /* * @notify Returns how many ancestor tokens are offered for one descendant token */ function ancestorPerDescendant() public view returns (uint256) { return stakedSupply == 0 ? WAD : wdivide(depositedAncestor(), stakedSupply); } /* * @notify Returns how many descendant tokens are offered for one ancestor token */ function descendantPerAncestor() public view returns (uint256) { return stakedSupply == 0 ? WAD : wdivide(stakedSupply, depositedAncestor()); } /* * @notify Given a custom amount of ancestor tokens, it returns the corresponding amount of descendant tokens to mint when someone joins * @param wad The amount of ancestor tokens to compute the descendant tokens for */ function joinPrice(uint256 wad) public view returns (uint256) { return wmultiply(wad, descendantPerAncestor()); } /* * @notify Given a custom amount of descendant tokens, it returns the corresponding amount of ancestor tokens to send when someone exits * @param wad The amount of descendant tokens to compute the ancestor tokens for */ function exitPrice(uint256 wad) public view returns (uint256) { return wmultiply(wad, ancestorPerDescendant()); } /* * @notice Returns whether the protocol is underwater or not */ function protocolUnderwater() public view returns (bool) { uint256 unqueuedUnauctionedDebt = accountingEngine.unqueuedUnauctionedDebt(); return both( accountingEngine.debtAuctionBidSize() <= unqueuedUnauctionedDebt, safeEngine.coinBalance(address(accountingEngine)) < unqueuedUnauctionedDebt ); } /* * @notice Burn descendant tokens in exchange for getting ancestor tokens from this contract * @return Whether the pool can auction ancestor tokens */ function canAuctionTokens() public view returns (bool) { return both( both(protocolUnderwater(), addition(minStakedTokensToKeep, tokensToAuction) <= depositedAncestor()), auctionHouse.activeStakedTokenAuctions() < maxConcurrentAuctions ); } /* * @notice Returns whether the system can mint new ancestor tokens */ function canPrintProtocolTokens() public view returns (bool) { return both( !canAuctionTokens(), either(auctionHouse.activeStakedTokenAuctions() == 0, bypassAuctions) ); } /* * @notice Returns unclaimed rewards for a given user */ function pendingRewards(address user) public view returns (uint256) { uint accTokensPerShare_ = accTokensPerShare; if (block.number > lastRewardBlock && stakedSupply != 0) { uint increaseInBalance = (block.number - lastRewardBlock) * rewardDripper.rewardPerBlock(); accTokensPerShare_ = addition(accTokensPerShare_, multiply(increaseInBalance, RAY) / stakedSupply); } return subtract(multiply(descendantBalanceOf[user], accTokensPerShare_) / RAY, rewardDebt[user]); } /* * @notice Returns rewards earned per block for each token deposited (WAD) */ function rewardRate() public view returns (uint256) { if (stakedSupply == 0) return 0; return (rewardDripper.rewardPerBlock() * WAD) / stakedSupply; } // --- Core Logic --- /* * @notify Updates the pool and pays rewards (if any) * @dev Must be included in deposits and withdrawals */ modifier payRewards() { updatePool(); if (descendantBalanceOf[msg.sender] > 0 && rewardPool.balance() > 0) { // Pays the reward uint256 pending = subtract(multiply(descendantBalanceOf[msg.sender], accTokensPerShare) / RAY, rewardDebt[msg.sender]); uint256 vested; if (both(address(escrow) != address(0), escrowPaused == 0)) { vested = multiply(pending, percentageVested) / 100; try escrow.escrowRewards(msg.sender, vested) { rewardPool.transfer(address(escrow), vested); emit EscrowRewards(address(escrow), msg.sender, vested); } catch(bytes memory revertReason) { emit FailEscrowRewards(revertReason); } } rewardPool.transfer(msg.sender, subtract(pending, vested)); rewardsBalance = rewardPool.balance(); emit RewardsPaid(msg.sender, pending); } _; rewardDebt[msg.sender] = multiply(descendantBalanceOf[msg.sender], accTokensPerShare) / RAY; } /* * @notify Pays outstanding rewards to msg.sender */ function getRewards() external nonReentrant payRewards {} /* * @notify Pull funds from the dripper */ function pullFunds() public { rewardDripper.dripReward(address(rewardPool)); } /* * @notify Updates pool data */ function updatePool() public { if (block.number <= lastRewardBlock) return; lastRewardBlock = block.number; if (stakedSupply == 0) return; pullFunds(); uint256 increaseInBalance = subtract(rewardPool.balance(), rewardsBalance); rewardsBalance = addition(rewardsBalance, increaseInBalance); // Updates distribution info accTokensPerShare = addition(accTokensPerShare, multiply(increaseInBalance, RAY) / stakedSupply); emit PoolUpdated(accTokensPerShare, stakedSupply); } /* * @notify Create a new auction that sells ancestor tokens in exchange for system coins */ function auctionAncestorTokens() external nonReentrant { require(canAuctionTokens(), "GebLenderFirstResortRewardsVested/cannot-auction-tokens"); ancestorPool.transfer(address(this), tokensToAuction); ancestorPool.token().approve(address(auctionHouse), tokensToAuction); auctionHouse.startAuction(tokensToAuction, systemCoinsToRequest); updatePool(); emit AuctionAncestorTokens(address(auctionHouse), tokensToAuction, systemCoinsToRequest); } /* * @notify Join ancestor tokens * @param wad The amount of ancestor tokens to join */ function join(uint256 wad) external nonReentrant payRewards { require(both(canJoin, !protocolUnderwater()), "GebLenderFirstResortRewardsVested/join-not-allowed"); require(wad > 0, "GebLenderFirstResortRewardsVested/null-ancestor-to-join"); uint256 price = joinPrice(wad); require(price > 0, "GebLenderFirstResortRewardsVested/null-join-price"); require(ancestorPool.token().transferFrom(msg.sender, address(ancestorPool), wad), "GebLenderFirstResortRewardsVested/could-not-transfer-ancestor"); descendant.mint(msg.sender, price); descendantBalanceOf[msg.sender] = addition(descendantBalanceOf[msg.sender], price); stakedSupply = addition(stakedSupply, price); emit Join(msg.sender, price, wad); } /* * @notice Request an exit for a specific amount of ancestor tokens * @param wad The amount of tokens to exit */ function requestExit(uint wad) external nonReentrant payRewards { require(wad > 0, "GebLenderFirstResortRewardsVested/null-amount-to-exit"); exitRequests[msg.sender].deadline = addition(now, exitDelay); exitRequests[msg.sender].lockedAmount = addition(exitRequests[msg.sender].lockedAmount, wad); descendantBalanceOf[msg.sender] = subtract(descendantBalanceOf[msg.sender], wad); descendant.burn(msg.sender, wad); emit RequestExit(msg.sender, exitRequests[msg.sender].deadline, wad); } /* * @notify Exit ancestor tokens */ function exit() external nonReentrant { require(both(now >= exitRequests[msg.sender].deadline, exitRequests[msg.sender].lockedAmount > 0), "GebLenderFirstResortRewardsVested/wait-more"); require(either(!protocolUnderwater(), forcedExit), "GebLenderFirstResortRewardsVested/exit-not-allowed"); uint256 price = exitPrice(exitRequests[msg.sender].lockedAmount); stakedSupply = subtract(stakedSupply, exitRequests[msg.sender].lockedAmount); ancestorPool.transfer(msg.sender, price); emit Exit(msg.sender, price, exitRequests[msg.sender].lockedAmount); delete exitRequests[msg.sender]; } }
@notify Updates pool data/ Updates distribution info
function updatePool() public { if (block.number <= lastRewardBlock) return; lastRewardBlock = block.number; if (stakedSupply == 0) return; pullFunds(); uint256 increaseInBalance = subtract(rewardPool.balance(), rewardsBalance); rewardsBalance = addition(rewardsBalance, increaseInBalance); accTokensPerShare = addition(accTokensPerShare, multiply(increaseInBalance, RAY) / stakedSupply); emit PoolUpdated(accTokensPerShare, stakedSupply); }
1,791,075
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./ActionRouteRegistry.sol"; import "./MinLibBytes.sol"; import "./RelayJob.sol"; /** * Manages message state flows */ contract StateRelayer is MessageRoute { ActionRouteRegistry public registry; RelayJob public relayJob; constructor( address wfRegistry, address relayJobService ) public { relayJob = RelayJob(relayJobService); registry = ActionRouteRegistry(wfRegistry); } function revertWithData(bytes memory data) internal pure { assembly { revert(add(data,32), mload(data)) } } /** * @dev execute conditions * @param controller contract address * @param selector function name * @param jobId job id */ function executeActionConditions( address controller, bytes4 selector, uint jobId ) public returns (bool) { // check if it has been whitelisted and purchased require(registry.getAction(controller, selector).conditions.length > 0, "Missing action key"); require( relayJob.hasInit(jobId), "Job already completed" ); ActionRoute memory item = registry.getAction(controller, selector); // check if it has been whitelisted and purchased require(item.controller != address(0), "Missing topic key"); bool conditionsCompleted = true; for (uint i = 0;i<item.conditions.length;i++) { (bool ok, bytes memory res) = item .controller .call( abi.encodeWithSelector( item.conditions[i], msg.sender, relayJob.get(jobId).response ) ); if (!ok){ //re-throw the revert with the same revert reason. revertWithData(res); return true; } (bool conditionResult) = abi.decode(res, (bool)); item.conditionStatus[i] = conditionResult; conditionsCompleted = conditionsCompleted && conditionResult; } if (conditionsCompleted == true) { relayJob.get(jobId).status = 2; emit MessageRequestCompleted( item.controller, item.selector, jobId ); } return true; } }
execute conditions controller contract address selector function name jobId job id/ check if it has been whitelisted and purchased check if it has been whitelisted and purchasedre-throw the revert with the same revert reason.
function executeActionConditions( address controller, bytes4 selector, uint jobId ) public returns (bool) { require(registry.getAction(controller, selector).conditions.length > 0, "Missing action key"); require( relayJob.hasInit(jobId), "Job already completed" ); ActionRoute memory item = registry.getAction(controller, selector); require(item.controller != address(0), "Missing topic key"); bool conditionsCompleted = true; for (uint i = 0;i<item.conditions.length;i++) { (bool ok, bytes memory res) = item .controller .call( abi.encodeWithSelector( item.conditions[i], msg.sender, relayJob.get(jobId).response ) ); if (!ok){ revertWithData(res); return true; } (bool conditionResult) = abi.decode(res, (bool)); item.conditionStatus[i] = conditionResult; conditionsCompleted = conditionsCompleted && conditionResult; } if (conditionsCompleted == true) { relayJob.get(jobId).status = 2; emit MessageRequestCompleted( item.controller, item.selector, jobId ); } return true; }
13,009,599
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @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(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * 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, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @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(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(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) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(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, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(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` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.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. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @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) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // 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) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @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 */ contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; 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 ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. 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 * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(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 */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. 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 * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(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 (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @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 ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ 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 ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ 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 ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
Calculates the origination fee added to a given borrowAmount This is simply `(1 + originationFee) borrowAmount` return Return value is expressed in 1e18 scale/ When origination fee is zero, the amount with fee is simply equal to the amount
function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); }
80,933
pragma solidity ^0.4.24; library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } 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; } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Rays is ERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) private allowed; uint256 internal totalSupply_; event Burn(address indexed burner, uint256 value); string public name = "Rays Network"; string public symbol = "RAYS"; uint8 public decimals = 18; uint256 public constant INITIAL_SUPPLY = 500000000 * 10**18; constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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]; } /** * @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 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(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _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 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(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; } /** * @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, uint256 _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, uint256 _subtractedValue ) public returns (bool) { uint256 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; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) public onlyOwner { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) public onlyOwner { require(_account != 0); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } } contract Crowdsale is Rays { // ICO rounds enum IcoStages {preSale, preIco, ico} IcoStages Stage; bool private crowdsaleFinished; uint private startPreSaleDate; uint private endPreSaleDate; uint public preSaleGoal; uint private preSaleRaised; uint private startPreIcoDate; uint private endPreIcoDate; uint public preIcoGoal; uint private preIcoRaised; uint private startIcoDate; uint private endIcoDate; uint public icoGoal; uint private icoRaised; uint private softCup; // 2 000 000 $ (300$ = 1 ether) uint private totalCup; uint private price; uint private total; uint private reserved; uint private hardCup;// 20 000 000 $ (300$ = 1 ether) struct Benefeciary{ // collect all participants of ICO address wallet; uint amount; } Benefeciary[] private benefeciary; uint private ethersRefund; constructor() public { startPreSaleDate = 1534723200; // insert here your pre sale start date endPreSaleDate = 1536969600; // insert here your pre sale end date preSaleGoal = 60000000; // pre-sale goal preSaleRaised = 0; // raised on pre-sale stage startPreIcoDate = 1534723200; // insert here your pre ico start date endPreIcoDate = 1538265600; // insert here your pre ico end date preIcoGoal = 60000000; // pre ico goal preIcoRaised = 0; // raised on pre ico startIcoDate = 1534723200; // insert here your ico start date endIcoDate = 1546214400; // insert here your ico end date icoGoal = 80000000; // ico goal icoRaised = 0; // raised on ico stage softCup = 6670 * 10**18; hardCup = 66670 * 10**18; totalCup = 0; price = 1160; total = preSaleGoal + preIcoGoal + icoGoal; reserved = (70000000 + 200000000 + 5000000 + 25000000) * 10**18; crowdsaleFinished = false; } function getCrowdsaleInfo() private returns(uint stage, uint tokenAvailable, uint bonus){ // Token calculating if(now <= endPreSaleDate && preSaleRaised < preSaleGoal){ Stage = IcoStages.preSale; tokenAvailable = preSaleGoal - preSaleRaised; total -= preSaleRaised; bonus = 0; // insert your bonus value on pre sale phase } else if(startPreIcoDate <= now && now <= endPreIcoDate && preIcoRaised < preIcoGoal){ Stage = IcoStages.preIco; tokenAvailable = preIcoGoal - preIcoRaised; total -= preIcoRaised; bonus = 50; // + 50% seems like bonus } else if(startIcoDate <= now && now <= endIcoDate && icoRaised < total){ tokenAvailable = total - icoRaised; Stage = IcoStages.ico; bonus = 0; } else { // if ICO has not been started revert(); } return (uint(Stage), tokenAvailable, bonus); } //per 0.1 ether will recieved 116 tokens function evaluateTokens(uint _value, address _sender) private returns(uint tokens){ ethersRefund = 0; uint bonus; uint tokenAvailable; uint stage; (stage,tokenAvailable,bonus) = getCrowdsaleInfo(); tokens = _value * price / 10**18; if(bonus != 0){ tokens = tokens + (tokens * bonus / 100); // calculate bonus tokens } if(tokenAvailable < tokens){ // if not enough tokens in reserve tokens = tokenAvailable; ethersRefund = _value - (tokens / price * 10**18); // calculate how many ethers will respond to user _sender.transfer(ethersRefund);// payback } owner.transfer(_value - ethersRefund); // Add token value to raised variable if(stage == 0){ preSaleRaised += tokens; } else if(stage == 1){ preIcoRaised += tokens; } else if(stage == 2){ icoRaised += tokens; } addInvestor(_sender, _value); return tokens; } function addInvestor(address _sender, uint _value) private { Benefeciary memory ben; for(uint i = 0; i < benefeciary.length; i++){ if(benefeciary[i].wallet == _sender){ benefeciary[i].amount = benefeciary[i].amount + _value - ethersRefund; } } ben.wallet = msg.sender; ben.amount = msg.value - ethersRefund; benefeciary.push(ben); } function() public payable { require(startPreSaleDate <= now && now <= endIcoDate); require(msg.value >= 0.1 ether); require(!crowdsaleFinished); totalCup += msg.value; uint token = evaluateTokens(msg.value, msg.sender); // send tokens to buyer balances[msg.sender] = balances[msg.sender].add(token * 10**18); balances[owner] = balances[owner].sub(token * 10**18); emit Transfer(owner, msg.sender, token * 10**18); } function showParticipantWei(address _wallet) public view onlyOwner returns(uint){ for(uint i = 0; i < benefeciary.length; i++){ if(benefeciary[i].wallet == _wallet){ return benefeciary[i].amount;// show in wei } } return 0; } function burnUnsoldTokens() public onlyOwner icoHasFinished{ _burn(owner, balanceOf(owner).sub(reserved)); } function crowdSaleStage() public view returns(string){ string memory result; if(uint(Stage) == 0){ result = "Pre Sale"; } else if(uint(Stage) == 1){ result = "Pre-ICO"; } else if(uint(Stage) == 2){ result = "ICO"; } return result; } function preSaleRaise() public view returns(uint){ return preSaleRaised; } function preIcoRaise() public view returns(uint){ return preIcoRaised; } function icoRaise() public view returns(uint){ return icoRaised; } modifier icoHasFinished() { require(now >= endIcoDate || icoRaised == total || crowdsaleFinished); _; } function endIcoByCup() public onlyOwner{ require(!crowdsaleFinished); require(totalCup >= softCup && totalCup <= hardCup); crowdsaleFinished = true; } // Output all funds in wei function showAllFunds() public onlyOwner view returns(uint){ return totalCup; } }
Internal function that burns an amount of the token of a given account. _account The account whose tokens will be burnt. _amount The amount that will be burnt./
function _burn(address _account, uint256 _amount) public onlyOwner { require(_account != 0); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); }
12,656,303
//Address: 0x0b6659a1a55c5038e34e8b0eeb9630c787466858 //Contract name: PentacoreCrowdsale //Balance: 0 Ether //Verification Date: 4/26/2018 //Transacion Count: 13 // CODE STARTS HERE pragma solidity ^0.4.21; // File: zeppelin-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) { 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 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) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ 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]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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 balance) { return balances[_owner]; } } // File: zeppelin-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: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ 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); 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; 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); 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/PentacoreToken.sol /** * @title Smart Contract which defines the token managed by the Pentacore Hedge Fund. * @author Jordan Stojanovski */ contract PentacoreToken is StandardToken { using SafeMath for uint256; string public name = 'PentacoreToken'; string public symbol = 'PENT'; uint256 public constant million = 1000000; uint256 public constant tokenCap = 1000 * million; // one billion tokens bool public isPaused = true; // Unlike the common practice to put the whitelist checks in the crowdsale, // the PentacoreToken does these tests itself. This is mandated by legal // issues, as follows: // - The exchange can be anywhere and it should not be concerned with // Pentacore's whitelisting methods. If the exchange desires, it can // perform its own KYC. // - Even after the Crowdsale / ICO if a whitelisted owner tries to sell // their tokens to a non-whitelisted buyer (address), the seller shall be // directed to the KYC process to be whitelisted before the sale can proceed. // This prevents against selling tokens to buyers under embargo. // - If the seller is removed from the whitelist prior to the sale attempt, // the corresponding sale should be reported to the authorities instead of // allowing the seller to proceed. This is subject of further discussion. mapping(address => bool) public whitelist; // If set to true, allow transfers between any addresses regardless of whitelist. // However, sale and/or redemption would still be not allowed regardless of this flag. // In the future, if it is determined that it is legal to transfer but not sell and/or redeem, // we could turn this flag on. bool public isFreeTransferAllowed = false; uint256 public tokenNAVMicroUSD; // Net Asset Value per token in MicroUSD (millionths of 1 US$) uint256 public weiPerUSD; // How many Wei is one US$ // Who's Who address public owner; // The owner of this contract. address public kycAdmin; // The address of the caller which can update the KYC status of an address. address public navAdmin; // The address of the caller which can update the NAV/USD and ETH/USD values. address public crowdsale; //The address of the crowdsale contract. address public redemption; // The address of the redemption contract. address public distributedAutonomousExchange; // The address of the exchange contract. event Mint(address indexed to, uint256 amount); event Burn(uint256 amount); event AddToWhitelist(address indexed beneficiary); event RemoveFromWhitelist(address indexed beneficiary); function PentacoreToken() public { owner = msg.sender; tokenNAVMicroUSD = million; // Initially 1 PENT = 1 US$ (a million millionths) isFreeTransferAllowed = false; isPaused = true; totalSupply_ = 0; // No tokens exist at creation. They are minted as sold. } /** * @dev Throws if called by any account other than the authorized one. * @param authorized the address of the authorized caller. */ modifier onlyBy(address authorized) { require(authorized != address(0)); require(msg.sender == authorized); _; } /** * @dev Pauses / unpauses the transferability of the token. * @param _pause pause if true; unpause if false */ function setPaused(bool _pause) public { require(owner != address(0)); require(msg.sender == owner); isPaused = _pause; } modifier notPaused() { require(!isPaused); _; } /** * @dev Sets the address of the owner. * @param _address The address of the new owner of the Token Contract. */ function transferOwnership(address _address) external onlyBy(owner) { require(_address != address(0)); // Prevent rendering it unusable owner = _address; } /** * @dev Sets the address of the PentacoreCrowdsale contract. * @param _address PentacoreCrowdsale contract address. */ function setKYCAdmin(address _address) external onlyBy(owner) { kycAdmin = _address; } /** * @dev Sets the address of the PentacoreCrowdsale contract. * @param _address PentacoreCrowdsale contract address. */ function setNAVAdmin(address _address) external onlyBy(owner) { navAdmin = _address; } /** * @dev Sets the address of the PentacoreCrowdsale contract. * @param _address PentacoreCrowdsale contract address. */ function setCrowdsaleContract(address _address) external onlyBy(owner) { crowdsale = _address; } /** * @dev Sets the address of the PentacoreRedemption contract. * @param _address PentacoreRedemption contract address. */ function setRedemptionContract(address _address) external onlyBy(owner) { redemption = _address; } /** * @dev Sets the address of the DistributedAutonomousExchange contract. * @param _address DistributedAutonomousExchange contract address. */ function setDistributedAutonomousExchange(address _address) external onlyBy(owner) { distributedAutonomousExchange = _address; } /** * @dev Sets the token price in US$. Set by owner to reflect NAV/token. * @param _price PentacoreToken price in USD. */ function setTokenNAVMicroUSD(uint256 _price) external onlyBy(navAdmin) { tokenNAVMicroUSD = _price; } /** * @dev Sets the token price in US$. Set by owner to reflect NAV/token. * @param _price PentacoreToken price in USD. */ function setWeiPerUSD(uint256 _price) external onlyBy(navAdmin) { weiPerUSD = _price; } /** * @dev Calculate the amount of Wei for a given token amount. The result is rounded down (floored) to a millionth of a US$) * @param _tokenAmount Whole number of tokens to be converted to Wei * @return amount of Wei for the given amount of tokens */ function tokensToWei(uint256 _tokenAmount) public view returns (uint256) { require(tokenNAVMicroUSD != uint256(0)); require(weiPerUSD != uint256(0)); return _tokenAmount.mul(tokenNAVMicroUSD).mul(weiPerUSD).div(million); } /** * @dev Calculate the amount tokens for a given Wei amount and the amount of change in Wei. * @param _weiAmount Whole number of Wei to be converted to tokens * @return whole amount of tokens for the given amount in Wei * @return change in Wei that is not sufficient to buy a whole token */ function weiToTokens(uint256 _weiAmount) public view returns (uint256, uint256) { require(tokenNAVMicroUSD != uint256(0)); require(weiPerUSD != uint256(0)); uint256 tokens = _weiAmount.mul(million).div(weiPerUSD).div(tokenNAVMicroUSD); uint256 changeWei = _weiAmount.sub(tokensToWei(tokens)); return (tokens, changeWei); } /** * @dev Allows / disallows free transferability of tokens regardless of whitelist. * @param _isFreeTransferAllowed disregard whitelist if true; not if false */ function setFreeTransferAllowed(bool _isFreeTransferAllowed) public { require(owner != address(0)); require(msg.sender == owner); isFreeTransferAllowed = _isFreeTransferAllowed; } /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. * @param _beneficiary the address which must be whitelisted by the KYC process in order to pass. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Reverts if beneficiary is not whitelisted and isFreeTransferAllowed is false. Can be used when extending this contract. * @param _beneficiary the address which must be whitelisted by the KYC process in order to pass unless isFreeTransferAllowed. */ modifier isWhitelistedOrFreeTransferAllowed(address _beneficiary) { require(isFreeTransferAllowed || whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) public onlyBy(kycAdmin) { whitelist[_beneficiary] = true; emit AddToWhitelist(_beneficiary); } /** * @dev Adds list of addresses to whitelist. * @param _beneficiaries List of addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyBy(kycAdmin) { for (uint256 i = 0; i < _beneficiaries.length; i++) addToWhitelist(_beneficiaries[i]); } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) public onlyBy(kycAdmin) { whitelist[_beneficiary] = false; emit RemoveFromWhitelist(_beneficiary); } /** * @dev Removes list of addresses from whitelist. * @param _beneficiaries List of addresses to be removed to the whitelist */ function removeManyFromWhitelist(address[] _beneficiaries) external onlyBy(kycAdmin) { for (uint256 i = 0; i < _beneficiaries.length; i++) removeFromWhitelist(_beneficiaries[i]); } /** * @dev Function to mint tokens. We mint as we sell tokens (actually the PentacoreCrowdsale contract does). * @dev The recipient should be whitelisted. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyBy(crowdsale) isWhitelisted(_to) returns (bool) { // Should run even when the token is paused. require(tokenNAVMicroUSD != uint256(0)); require(weiPerUSD != uint256(0)); require(totalSupply_.add(_amount) <= tokenCap); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Function to burn tokens. We burn as owners redeem tokens (actually the PentacoreRedemptions contract does). * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function burn(uint256 _amount) public onlyBy(redemption) returns (bool) { // Should run even when the token is paused. require(balances[redemption].sub(_amount) >= uint256(0)); require(totalSupply_.sub(_amount) >= uint256(0)); balances[redemption] = balances[redemption].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); emit Burn(_amount); return true; } /** * @dev transfer token for a specified address * @dev Both the sender and the recipient should be whitelisted. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public notPaused isWhitelistedOrFreeTransferAllowed(msg.sender) isWhitelistedOrFreeTransferAllowed(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @dev The sender should be whitelisted. * * 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 notPaused isWhitelistedOrFreeTransferAllowed(msg.sender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * @dev The sender should be whitelisted. * * 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 notPaused isWhitelistedOrFreeTransferAllowed(msg.sender) returns (bool) { return super.increaseApproval(_spender, _addedValue); } /** * @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 * * @dev The sender does not need to be whitelisted. This is in case they are removed from white list and no longer agree to sell at an exchange. * @dev This function stays untouched (directly inherited), but it's re-defined for clarity: * * @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) { return super.decreaseApproval(_spender, _subtractedValue); } /** * @dev Transfer tokens from one address to another * @dev Both the sender and the recipient should be whitelisted. * @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 notPaused isWhitelistedOrFreeTransferAllowed(_from) isWhitelistedOrFreeTransferAllowed(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/PentacoreCrowdsale.sol /** * @title Allows payers to this contract to purchase Pentacore Tokens (PENT). * @author Jordan Stojanovski */ contract PentacoreCrowdsale { using SafeMath for uint256; uint256 public constant million = 1000000; uint256 public constant icoTokenCap = 50 * million; uint256 public constant minimumPurchase = 100; // amount of tokens uint public constant icoDuration = 4 weeks; uint256 public icoStart; bool public postICOSale = false; // The owner of this contracts address public owner; // The token being sold PentacoreToken public token; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; // // Amount raised in various currencies via external sales expressed as currency => valueRaised mapping (bytes32 => uint256) public externalFundsRaised; /** * @dev Sets the address of the owner. * @param _address The address of the new owner of this contract. */ function transferOwnership(address _address) external { require(msg.sender == owner); require(owner != address(0)); require(_address != address(0)); // Prevent rendering it unusable owner = _address; } /** * @dev Sets the address of the wallet where crowdsale prceeds end up. * @param _newWallet The address of the new wallet. */ function changeWallet(address _newWallet) external { require(msg.sender == owner); require(owner != address(0)); require(_newWallet != address(0)); // Prevent rendering it unusable wallet = _newWallet; } /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for external token purchase logging * @param purchaser who paid for the tokens * @param currency currency in which payment was processed * @param value units in specified currency paid for purchase * @param amount amount of tokens purchased * @param txid the transaction ID of the external deposit. Could be a Bitcoin Transaction Hash or Wire Transfer Reference Number. */ event ExternalTokenPurchase(address indexed purchaser, string currency, uint256 value, uint256 amount, uint256 txid); /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function PentacoreCrowdsale(address _wallet, PentacoreToken _token) public { owner = msg.sender; require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function startICO() external { require(owner != address(0)); require(msg.sender == owner); require(token != address(0)); require(icoStart == uint256(0)); icoStart = now; } function isICOActive() public view returns(bool) { return icoStart != 0 && now <= icoStart.add(icoDuration); } function setPostICOSale(bool _postICOSale) public { postICOSale = _postICOSale; } // ----------------------------------------- // PentacoreCrowdsale external interface // ----------------------------------------- /** * @dev fallback function */ function () external payable { buyTokens(); } /** * @dev Token Purchase */ function buyTokens() public payable { require(msg.value != 0); require(msg.sender != 0); require(isICOActive() || postICOSale); require(token.whitelist(msg.sender)); // calculate token amount to be created uint256 tokensPurchased; uint256 weiChange; (tokensPurchased, weiChange) = token.weiToTokens(msg.value); uint256 weiExactAmount = msg.value.sub(weiChange); require(tokensPurchased >= minimumPurchase); // Cannot exceed total allocated supply for the ICO // reverting allows a smaller purchase to pass in the future, up to the icoTokenCap if (isICOActive() && token.totalSupply().add(tokensPurchased) > icoTokenCap) revert(); // Update total amount raised from purchases in Wei weiRaised = weiRaised.add(weiExactAmount); // Issue the tokens token.mint(msg.sender, tokensPurchased); // will revert if tokenCap is reached emit TokenPurchase(msg.sender, weiExactAmount, tokensPurchased); // Process the payment wallet.transfer(weiExactAmount); msg.sender.transfer(weiChange); } /** * @dev This is separated as a function because it can be called separately to avoid costs as it is view only * @param _currency currency symbol * @return the hash of the currency (no security needed - just so it can be mapped) */ function currencyToHash(string _currency) public pure returns(bytes32) { return keccak256(_currency); } /** * @dev This is separated as a function because it can be called separately to avoid costs as it is view only * @param _currency currency symbol * @return the amount of funds externally raised in the given currency */ function getExternalFundsRaised(string _currency) public view returns(uint256) { return externalFundsRaised[currencyToHash(_currency)]; } /** * @dev Token Purchase outside of this contract, usually paid for by currencies other than ETH * @dev Only the owner of this contract can issue tokens in exchange for payments in other currencies * @param _beneficiary the address which receives the tokens * @param _currency currency symbol * @param _value amount paid in the given currency. It must be in whole units, so currencies like MicroUSD (millionth of a US$) should be used * @param _txid the transaction ID of the external deposit. Could be a Bitcoin Transaction Hash or Wire Transfer Reference Number. * @param _amount amount of tokens purchased */ function externalPurchase(address _beneficiary, string _currency, uint256 _value, uint256 _amount, uint256 _txid) public { require(owner != address(0)); require(msg.sender == owner); // Only owner can issue tokens in exchange for external payment require(isICOActive() || postICOSale); require(token.whitelist(_beneficiary)); require(_amount >= minimumPurchase); // Cannot exceed total allocated supply for the ICO // reverting allows a smaller purchase to pass in the future, up to the icoTokenCap if (isICOActive() && token.totalSupply().add(_amount) > icoTokenCap) revert(); // Update total amount raised from purchases via external sales externalFundsRaised[currencyToHash(_currency)] = externalFundsRaised[currencyToHash(_currency)].add(_value); // Issue the tokens token.mint(_beneficiary, _amount); // will revert if tokenCap is reached emit ExternalTokenPurchase(_beneficiary, _currency, _value, _amount, _txid); } }
Adds single address to whitelist. _beneficiary Address to be added to the whitelist/
function addToWhitelist(address _beneficiary) public onlyBy(kycAdmin) { whitelist[_beneficiary] = true; emit AddToWhitelist(_beneficiary); }
12,546,799