file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "../core/State.sol"; import "../events/LoanOpeningsEvents.sol"; import "../events/LoanMaintenanceEvents.sol"; import "../mixins/VaultController.sol"; import "../mixins/InterestUser.sol"; import "../mixins/LiquidationHelper.sol"; import "../swaps/SwapsUser.sol"; import "../mixins/ModuleCommonFunctionalities.sol"; /** * @title Loan Maintenance contract. * * @notice This contract code comes from bZx. bZx is a protocol for tokenized * margin trading and lending https://bzx.network similar to the dYdX protocol. * * This contract contains functions to query loan data and to modify its status * by withdrawing or depositing collateral. * */ contract LoanMaintenance is LoanOpeningsEvents, LoanMaintenanceEvents, VaultController, InterestUser, SwapsUser, LiquidationHelper, ModuleCommonFunctionalities { // Keep the old LoanReturnData for backward compatibility (especially for the watcher) struct LoanReturnData { bytes32 loanId; address loanToken; address collateralToken; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; /// collateralToLoanRate uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 endTimestamp; uint256 maxLiquidatable; uint256 maxSeizable; } // The new struct which contained borrower & creation time of a loan struct LoanReturnDataV2 { bytes32 loanId; address loanToken; address collateralToken; address borrower; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; /// collateralToLoanRate uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 endTimestamp; uint256 maxLiquidatable; uint256 maxSeizable; uint256 creationTimestamp; } /** * @notice Empty public constructor. * */ constructor() public {} /** * @notice Fallback function is to react to receiving value (rBTC). * */ function() external { revert("fallback not allowed"); } /** * @notice Set initial values of proxy targets. * * @param target The address of the logic contract instance. * */ function initialize(address target) external onlyOwner { address prevModuleContractAddress = logicTargets[this.depositCollateral.selector]; _setTarget(this.depositCollateral.selector, target); _setTarget(this.withdrawCollateral.selector, target); _setTarget(this.withdrawAccruedInterest.selector, target); _setTarget(this.extendLoanDuration.selector, target); _setTarget(this.reduceLoanDuration.selector, target); _setTarget(this.getLenderInterestData.selector, target); _setTarget(this.getLoanInterestData.selector, target); _setTarget(this.getUserLoans.selector, target); _setTarget(this.getUserLoansV2.selector, target); _setTarget(this.getLoan.selector, target); _setTarget(this.getLoanV2.selector, target); _setTarget(this.getActiveLoans.selector, target); _setTarget(this.getActiveLoansV2.selector, target); emit ProtocolModuleContractReplaced(prevModuleContractAddress, target, "LoanMaintenance"); } /** * @notice Increase the margin of a position by depositing additional collateral. * * @param loanId A unique ID representing the loan. * @param depositAmount The amount to be deposited in collateral tokens. * * @return actualWithdrawAmount The amount withdrawn taking into account drawdowns. * */ function depositCollateral( bytes32 loanId, uint256 depositAmount /// must match msg.value if ether is sent ) external payable nonReentrant whenNotPaused { require(depositAmount != 0, "depositAmount is 0"); Loan storage loanLocal = loans[loanId]; LoanParams storage loanParamsLocal = loanParams[loanLocal.loanParamsId]; require(loanLocal.active, "loan is closed"); require(msg.value == 0 || loanParamsLocal.collateralToken == address(wrbtcToken), "wrong asset sent"); loanLocal.collateral = loanLocal.collateral.add(depositAmount); if (msg.value == 0) { vaultDeposit(loanParamsLocal.collateralToken, msg.sender, depositAmount); } else { require(msg.value == depositAmount, "ether deposit mismatch"); vaultEtherDeposit(msg.sender, msg.value); } (uint256 collateralToLoanRate, ) = IPriceFeeds(priceFeeds).queryRate(loanParamsLocal.collateralToken, loanParamsLocal.loanToken); emit DepositCollateral(loanId, depositAmount, collateralToLoanRate); } /** * @notice Withdraw from the collateral. This reduces the margin of a position. * * @param loanId A unique ID representing the loan. * @param receiver The account getting the withdrawal. * @param withdrawAmount The amount to be withdrawn in collateral tokens. * * @return actualWithdrawAmount The amount withdrawn taking into account drawdowns. * */ function withdrawCollateral( bytes32 loanId, address receiver, uint256 withdrawAmount ) external nonReentrant whenNotPaused returns (uint256 actualWithdrawAmount) { require(withdrawAmount != 0, "withdrawAmount is 0"); Loan storage loanLocal = loans[loanId]; LoanParams storage loanParamsLocal = loanParams[loanLocal.loanParamsId]; require(loanLocal.active, "loan is closed"); require(msg.sender == loanLocal.borrower || delegatedManagers[loanLocal.id][msg.sender], "unauthorized"); uint256 maxDrawdown = IPriceFeeds(priceFeeds).getMaxDrawdown( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral, loanParamsLocal.maintenanceMargin ); if (withdrawAmount > maxDrawdown) { actualWithdrawAmount = maxDrawdown; } else { actualWithdrawAmount = withdrawAmount; } loanLocal.collateral = loanLocal.collateral.sub(actualWithdrawAmount); if (loanParamsLocal.collateralToken == address(wrbtcToken)) { vaultEtherWithdraw(receiver, actualWithdrawAmount); } else { vaultWithdraw(loanParamsLocal.collateralToken, receiver, actualWithdrawAmount); } } /** * @notice Withdraw accrued loan interest. * * @dev Wrapper for _payInterest internal function. * * @param loanToken The loan token address. * */ function withdrawAccruedInterest(address loanToken) external whenNotPaused { /// Pay outstanding interest to lender. _payInterest( msg.sender, /// Lender. loanToken ); } /** * @notice Extend the loan duration by as much time as depositAmount can buy. * * @param loanId A unique ID representing the loan. * @param depositAmount The amount to be deposited in loan tokens. Used to pay the interest for the new duration. * @param useCollateral Whether pay interests w/ the collateral. If true, depositAmount of loan tokens * will be purchased with the collateral. * // param calldata The payload for the call. These loan DataBytes are additional loan data (not in use for token swaps). * * @return secondsExtended The amount of time in seconds the loan is extended. * */ function extendLoanDuration( bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata /// loanDataBytes, for future use. ) external payable nonReentrant whenNotPaused returns (uint256 secondsExtended) { require(depositAmount != 0, "depositAmount is 0"); Loan storage loanLocal = loans[loanId]; LoanParams storage loanParamsLocal = loanParams[loanLocal.loanParamsId]; require(loanLocal.active, "loan is closed"); require(!useCollateral || msg.sender == loanLocal.borrower || delegatedManagers[loanLocal.id][msg.sender], "unauthorized"); require(loanParamsLocal.maxLoanTerm == 0, "indefinite-term only"); require(msg.value == 0 || (!useCollateral && loanParamsLocal.loanToken == address(wrbtcToken)), "wrong asset sent"); /// Pay outstanding interest to lender. _payInterest(loanLocal.lender, loanParamsLocal.loanToken); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, /// fee token loanParamsLocal.collateralToken, /// pairToken (used to check if there is any special rebates or not) -- to pay fee reward loanLocal.borrower, block.timestamp ); /// Handle back interest: calculates interest owned since the loan /// endtime passed but the loan remained open. uint256 backInterestOwed; if (block.timestamp > loanLocal.endTimestamp) { backInterestOwed = block.timestamp.sub(loanLocal.endTimestamp); backInterestOwed = backInterestOwed.mul(loanInterestLocal.owedPerDay); backInterestOwed = backInterestOwed.div(86400); require(depositAmount > backInterestOwed, "deposit cannot cover back interest"); } /// Deposit interest. if (useCollateral) { _doCollateralSwap(loanLocal, loanParamsLocal, depositAmount); } else { if (msg.value == 0) { vaultDeposit(loanParamsLocal.loanToken, msg.sender, depositAmount); } else { require(msg.value == depositAmount, "ether deposit mismatch"); vaultEtherDeposit(msg.sender, msg.value); } } if (backInterestOwed != 0) { depositAmount = depositAmount.sub(backInterestOwed); /// Pay out backInterestOwed _payInterestTransfer(loanLocal.lender, loanParamsLocal.loanToken, backInterestOwed); } secondsExtended = depositAmount.mul(86400).div(loanInterestLocal.owedPerDay); loanLocal.endTimestamp = loanLocal.endTimestamp.add(secondsExtended); require(loanLocal.endTimestamp > block.timestamp, "loan too short"); uint256 maxDuration = loanLocal.endTimestamp.sub(block.timestamp); /// Loan term has to at least be greater than one hour. require(maxDuration > 3600, "loan too short"); loanInterestLocal.depositTotal = loanInterestLocal.depositTotal.add(depositAmount); lenderInterest[loanLocal.lender][loanParamsLocal.loanToken].owedTotal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken] .owedTotal .add(depositAmount); } /** * @notice Reduce the loan duration by withdrawing from the deposited interest. * * @param loanId A unique ID representing the loan. * @param receiver The account getting the withdrawal. * @param withdrawAmount The amount to be withdrawn in loan tokens. * * @return secondsReduced The amount of time in seconds the loan is reduced. * */ function reduceLoanDuration( bytes32 loanId, address receiver, uint256 withdrawAmount ) external nonReentrant whenNotPaused returns (uint256 secondsReduced) { require(withdrawAmount != 0, "withdrawAmount is 0"); Loan storage loanLocal = loans[loanId]; LoanParams storage loanParamsLocal = loanParams[loanLocal.loanParamsId]; require(loanLocal.active, "loan is closed"); require(msg.sender == loanLocal.borrower || delegatedManagers[loanLocal.id][msg.sender], "unauthorized"); require(loanParamsLocal.maxLoanTerm == 0, "indefinite-term only"); require(loanLocal.endTimestamp > block.timestamp, "loan term has ended"); /// Pay outstanding interest to lender. _payInterest(loanLocal.lender, loanParamsLocal.loanToken); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, /// fee token loanParamsLocal.collateralToken, /// pairToken (used to check if there is any special rebates or not) -- to pay fee reward loanLocal.borrower, block.timestamp ); uint256 interestDepositRemaining = loanLocal.endTimestamp.sub(block.timestamp).mul(loanInterestLocal.owedPerDay).div(86400); require(withdrawAmount < interestDepositRemaining, "withdraw amount too high"); /// Withdraw interest. if (loanParamsLocal.loanToken == address(wrbtcToken)) { vaultEtherWithdraw(receiver, withdrawAmount); } else { vaultWithdraw(loanParamsLocal.loanToken, receiver, withdrawAmount); } secondsReduced = withdrawAmount.mul(86400).div(loanInterestLocal.owedPerDay); require(loanLocal.endTimestamp > secondsReduced, "loan too short"); loanLocal.endTimestamp = loanLocal.endTimestamp.sub(secondsReduced); require(loanLocal.endTimestamp > block.timestamp, "loan too short"); uint256 maxDuration = loanLocal.endTimestamp.sub(block.timestamp); /// Loan term has to at least be greater than one hour. require(maxDuration > 3600, "loan too short"); loanInterestLocal.depositTotal = loanInterestLocal.depositTotal.sub(withdrawAmount); lenderInterest[loanLocal.lender][loanParamsLocal.loanToken].owedTotal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken] .owedTotal .sub(withdrawAmount); } /** * @notice Get current lender interest data totals for all loans * with a specific oracle and interest token. * * @param lender The lender address. * @param loanToken The loan token address. * * @return interestPaid The total amount of interest that has been paid to a lender so far. * @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet. * @return interestOwedPerDay The amount of interest the lender is earning per day. * @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn. * @return interestFeePercent The fee retained by the protocol before interest is paid to the lender. * @return principalTotal The total amount of outstanding principal the lender has loaned. * */ function getLenderInterestData(address lender, address loanToken) external view returns ( uint256 interestPaid, uint256 interestPaidDate, uint256 interestOwedPerDay, uint256 interestUnPaid, uint256 interestFeePercent, uint256 principalTotal ) { LenderInterest memory lenderInterestLocal = lenderInterest[lender][loanToken]; interestUnPaid = block.timestamp.sub(lenderInterestLocal.updatedTimestamp).mul(lenderInterestLocal.owedPerDay).div(86400); if (interestUnPaid > lenderInterestLocal.owedTotal) interestUnPaid = lenderInterestLocal.owedTotal; return ( lenderInterestLocal.paidTotal, lenderInterestLocal.paidTotal != 0 ? lenderInterestLocal.updatedTimestamp : 0, lenderInterestLocal.owedPerDay, lenderInterestLocal.updatedTimestamp != 0 ? interestUnPaid : 0, lendingFeePercent, lenderInterestLocal.principalTotal ); } /** * @notice Get current interest data for a loan. * * @param loanId A unique ID representing the loan. * * @return loanToken The loan token that interest is paid in. * @return interestOwedPerDay The amount of interest the borrower is paying per day. * @return interestDepositTotal The total amount of interest the borrower has deposited. * @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender. * */ function getLoanInterestData(bytes32 loanId) external view returns ( address loanToken, uint256 interestOwedPerDay, uint256 interestDepositTotal, uint256 interestDepositRemaining ) { loanToken = loanParams[loans[loanId].loanParamsId].loanToken; interestOwedPerDay = loanInterest[loanId].owedPerDay; interestDepositTotal = loanInterest[loanId].depositTotal; uint256 endTimestamp = loans[loanId].endTimestamp; uint256 interestTime = block.timestamp > endTimestamp ? endTimestamp : block.timestamp; interestDepositRemaining = endTimestamp > interestTime ? endTimestamp.sub(interestTime).mul(interestOwedPerDay).div(86400) : 0; } /** * @notice Get all user loans. * * Only returns data for loans that are active. * * @param user The user address. * @param start The lower loan ID to start with. * @param count The maximum number of results. * @param loanType The type of loan. * loanType 0: all loans. * loanType 1: margin trade loans. * loanType 2: non-margin trade loans. * @param isLender Whether the user is lender or borrower. * @param unsafeOnly The safe filter (True/False). * * @return loansData The array of loans as query result. * */ function getUserLoans( address user, uint256 start, uint256 count, uint256 loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData) { EnumerableBytes32Set.Bytes32Set storage set = isLender ? lenderLoanSets[user] : borrowerLoanSets[user]; uint256 end = start.add(count).min256(set.length()); if (start >= end) { return loansData; } loansData = new LoanReturnData[](count); uint256 itemCount; for (uint256 i = end - start; i > 0; i--) { if (itemCount == count) { break; } LoanReturnData memory loanData = _getLoan( set.get(i + start - 1), /// loanId loanType, unsafeOnly ); if (loanData.loanId == 0) continue; loansData[itemCount] = loanData; itemCount++; } if (itemCount < count) { assembly { mstore(loansData, itemCount) } } } /** * @notice Get all user loans. * * Only returns data for loans that are active. * * @param user The user address. * @param start The lower loan ID to start with. * @param count The maximum number of results. * @param loanType The type of loan. * loanType 0: all loans. * loanType 1: margin trade loans. * loanType 2: non-margin trade loans. * @param isLender Whether the user is lender or borrower. * @param unsafeOnly The safe filter (True/False). * * @return loansData The array of loans as query result. * */ function getUserLoansV2( address user, uint256 start, uint256 count, uint256 loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnDataV2[] memory loansDataV2) { EnumerableBytes32Set.Bytes32Set storage set = isLender ? lenderLoanSets[user] : borrowerLoanSets[user]; uint256 end = start.add(count).min256(set.length()); if (start >= end) { return loansDataV2; } loansDataV2 = new LoanReturnDataV2[](count); uint256 itemCount; for (uint256 i = end - start; i > 0; i--) { if (itemCount == count) { break; } LoanReturnDataV2 memory loanDataV2 = _getLoanV2( set.get(i + start - 1), /// loanId loanType, unsafeOnly ); if (loanDataV2.loanId == 0) continue; loansDataV2[itemCount] = loanDataV2; itemCount++; } if (itemCount < count) { assembly { mstore(loansDataV2, itemCount) } } } /** * @notice Get one loan data structure by matching ID. * * Wrapper to internal _getLoan call. * * @param loanId A unique ID representing the loan. * * @return loansData The data structure w/ loan information. * */ function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData) { return _getLoan( loanId, 0, /// loanType false /// unsafeOnly ); } /** * @notice Get one loan data structure by matching ID. * * Wrapper to internal _getLoan call. * * @param loanId A unique ID representing the loan. * * @return loansData The data structure w/ loan information. * */ function getLoanV2(bytes32 loanId) external view returns (LoanReturnDataV2 memory loanDataV2) { return _getLoanV2( loanId, 0, /// loanType false /// unsafeOnly ); } /** * @notice Get all active loans. * * @param start The lower loan ID to start with. * @param count The maximum number of results. * @param unsafeOnly The safe filter (True/False). * * @return loansData The data structure w/ loan information. * */ function getActiveLoans( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData) { uint256 end = start.add(count).min256(activeLoansSet.length()); if (start >= end) { return loansData; } loansData = new LoanReturnData[](count); uint256 itemCount; for (uint256 i = end - start; i > 0; i--) { if (itemCount == count) { break; } LoanReturnData memory loanData = _getLoan( activeLoansSet.get(i + start - 1), /// loanId 0, /// loanType unsafeOnly ); if (loanData.loanId == 0) continue; loansData[itemCount] = loanData; itemCount++; } if (itemCount < count) { assembly { mstore(loansData, itemCount) } } } /** * @dev New view function which will return the loan data. * @dev This function was created to support backward compatibility * @dev As in we the old getActiveLoans function is not expected to be changed by the wathcers. * * @param start The lower loan ID to start with. * @param count The maximum number of results. * @param unsafeOnly The safe filter (True/False). * * @return loanData The data structure * @return extendedLoanData The data structure which contained (borrower & creation time) */ function getActiveLoansV2( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnDataV2[] memory loansDataV2) { uint256 end = start.add(count).min256(activeLoansSet.length()); if (start >= end) { return loansDataV2; } loansDataV2 = new LoanReturnDataV2[](count); uint256 itemCount; for (uint256 i = end - start; i > 0; i--) { if (itemCount == count) { break; } LoanReturnDataV2 memory loanDataV2 = _getLoanV2( activeLoansSet.get(i + start - 1), /// loanId 0, /// loanType unsafeOnly ); if (loanDataV2.loanId == 0) continue; loansDataV2[itemCount] = loanDataV2; itemCount++; } if (itemCount < count) { assembly { mstore(loansDataV2, itemCount) } } } /** * @notice Internal function to get one loan data structure. * * @param loanId A unique ID representing the loan. * @param loanType The type of loan. * loanType 0: all loans. * loanType 1: margin trade loans. * loanType 2: non-margin trade loans. * @param unsafeOnly The safe filter (True/False). * * @return loansData The data structure w/ the loan information. * */ function _getLoan( bytes32 loanId, uint256 loanType, bool unsafeOnly ) internal view returns (LoanReturnData memory loanData) { Loan memory loanLocal = loans[loanId]; LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; if (loanType != 0) { if (!((loanType == 1 && loanParamsLocal.maxLoanTerm != 0) || (loanType == 2 && loanParamsLocal.maxLoanTerm == 0))) { return loanData; } } LoanInterest memory loanInterestLocal = loanInterest[loanId]; (uint256 currentMargin, uint256 collateralToLoanRate) = IPriceFeeds(priceFeeds).getCurrentMargin( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ); uint256 maxLiquidatable; uint256 maxSeizable; if (currentMargin <= loanParamsLocal.maintenanceMargin) { (maxLiquidatable, maxSeizable, ) = _getLiquidationAmounts( loanLocal.principal, loanLocal.collateral, currentMargin, loanParamsLocal.maintenanceMargin, collateralToLoanRate ); } else if (unsafeOnly) { return loanData; } return LoanReturnData({ loanId: loanId, loanToken: loanParamsLocal.loanToken, collateralToken: loanParamsLocal.collateralToken, principal: loanLocal.principal, collateral: loanLocal.collateral, interestOwedPerDay: loanInterestLocal.owedPerDay, interestDepositRemaining: loanLocal.endTimestamp >= block.timestamp ? loanLocal.endTimestamp.sub(block.timestamp).mul(loanInterestLocal.owedPerDay).div(86400) : 0, startRate: loanLocal.startRate, startMargin: loanLocal.startMargin, maintenanceMargin: loanParamsLocal.maintenanceMargin, currentMargin: currentMargin, maxLoanTerm: loanParamsLocal.maxLoanTerm, endTimestamp: loanLocal.endTimestamp, maxLiquidatable: maxLiquidatable, maxSeizable: maxSeizable }); } /** * @notice Internal function to get one loan data structure v2. * * @param loanId A unique ID representing the loan. * @param loanType The type of loan. * loanType 0: all loans. * loanType 1: margin trade loans. * loanType 2: non-margin trade loans. * @param unsafeOnly The safe filter (True/False). * * @return loansData The data v2 structure w/ the loan information. * */ function _getLoanV2( bytes32 loanId, uint256 loanType, bool unsafeOnly ) internal view returns (LoanReturnDataV2 memory loanDataV2) { Loan memory loanLocal = loans[loanId]; LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; if (loanType != 0) { if (!((loanType == 1 && loanParamsLocal.maxLoanTerm != 0) || (loanType == 2 && loanParamsLocal.maxLoanTerm == 0))) { return loanDataV2; } } LoanInterest memory loanInterestLocal = loanInterest[loanId]; (uint256 currentMargin, uint256 collateralToLoanRate) = IPriceFeeds(priceFeeds).getCurrentMargin( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ); uint256 maxLiquidatable; uint256 maxSeizable; if (currentMargin <= loanParamsLocal.maintenanceMargin) { (maxLiquidatable, maxSeizable, ) = _getLiquidationAmounts( loanLocal.principal, loanLocal.collateral, currentMargin, loanParamsLocal.maintenanceMargin, collateralToLoanRate ); } else if (unsafeOnly) { return loanDataV2; } return LoanReturnDataV2({ loanId: loanId, loanToken: loanParamsLocal.loanToken, collateralToken: loanParamsLocal.collateralToken, borrower: loanLocal.borrower, principal: loanLocal.principal, collateral: loanLocal.collateral, interestOwedPerDay: loanInterestLocal.owedPerDay, interestDepositRemaining: loanLocal.endTimestamp >= block.timestamp ? loanLocal.endTimestamp.sub(block.timestamp).mul(loanInterestLocal.owedPerDay).div(86400) : 0, startRate: loanLocal.startRate, startMargin: loanLocal.startMargin, maintenanceMargin: loanParamsLocal.maintenanceMargin, currentMargin: currentMargin, maxLoanTerm: loanParamsLocal.maxLoanTerm, endTimestamp: loanLocal.endTimestamp, maxLiquidatable: maxLiquidatable, maxSeizable: maxSeizable, creationTimestamp: loanLocal.startTimestamp }); } /** * @notice Internal function to collect interest from the collateral. * * @param loanLocal The loan object. * @param loanParamsLocal The loan parameters. * @param depositAmount The amount of underlying tokens provided on the loan. * */ function _doCollateralSwap( Loan storage loanLocal, LoanParams memory loanParamsLocal, uint256 depositAmount ) internal { /// Reverts in _loanSwap if amountNeeded can't be bought. (, uint256 sourceTokenAmountUsed, ) = _loanSwap( loanLocal.id, loanParamsLocal.collateralToken, loanParamsLocal.loanToken, loanLocal.borrower, loanLocal.collateral, /// minSourceTokenAmount 0, /// maxSourceTokenAmount (0 means minSourceTokenAmount) depositAmount, /// requiredDestTokenAmount (partial spend of loanLocal.collateral to fill this amount) true, /// bypassFee "" /// loanDataBytes ); loanLocal.collateral = loanLocal.collateral.sub(sourceTokenAmountUsed); /// Ensure the loan is still healthy. (uint256 currentMargin, ) = IPriceFeeds(priceFeeds).getCurrentMargin( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ); require(currentMargin > loanParamsLocal.maintenanceMargin, "unhealthy position"); } }
Get one loan data structure by matching ID. Wrapper to internal _getLoan call. loanId A unique ID representing the loan. return loansData The data structure w/ loan information. /
function getLoanV2(bytes32 loanId) external view returns (LoanReturnDataV2 memory loanDataV2) { return _getLoanV2( loanId, ); }
897,195
/** *Submitted for verification at Etherscan.io on 2021-09-25 */ // File: node_modules\@openzeppelin\contracts\utils\Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 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 <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; } } // 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\ReentrancyGuard.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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: @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: node_modules\@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: node_modules\@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\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: contracts\ITreasure.sol pragma solidity ^0.7.6; /** * @dev Interface of the Hashquest's Treasure contract. */ interface ITreasure { /** * @dev Payable method meant to fill the contract's balance. */ function fillTreasure() external payable returns (bool); } // File: contracts\Treasure.sol pragma solidity ^0.7.6; contract Treasure is ReentrancyGuard, Ownable, ITreasure { using SafeMath for uint256; using Address for address; uint8 public constant MIN_BLOCK_DELAY = 20; // Min block delay to accept an answer uint8 public BLOCK_DELAY = 20; // Current block delay to accept an answer // Keeps track of all the transfers sent to fillTreasure() - Incremental only uint256 public historicalTreasure; // Stores the hash of the quest answers. questId: answerHash mapping (uint8 => bytes32) public questAnswers; // Stores answers precommits - FrontRunning mitigation struct Precommit { bytes32 commitAnswer; uint256 block; } mapping (address => Precommit) precommitRecords; // Stores data of a quest winner. struct Winner { bool prizeClaimed; uint256 timestamp; uint256 nftId; uint256 paid; string answer; } mapping (uint8 => Winner) public prizeWinners; // questId: Winner address public _hashquestsContract; event treasureFilled(uint256 deposit, uint256 treasureBalance, uint256 historicalTreasure); event completedQuest(uint256 NFTId, string answer, address recipient, uint8 questId); event winnerCollectedPrize(uint256 valueCollected, uint256 NFTId, uint8 questId, address recipient); constructor(address hashquestsContract) ReentrancyGuard() { _hashquestsContract = hashquestsContract; // Correct answers for each quest questAnswers[1] = 0xd2cd94afe63a799d251a5209b25585cb10fe3ecf43c6c9e5250f477d11369c6f; questAnswers[2] = 0xec3026cfc4cea5f2c36c346ba91203504fcf60aaafd72614e785e1a31581e716; questAnswers[3] = 0xb32513bf27f6874ff2196e84f72fa973f5a2260668ae4faf37d37e409e3b19ab; questAnswers[4] = 0x7f4f10fdcb2a95fef25e212ee74d27f4477e198b7bb4c9e18281e4f55b499f19; questAnswers[5] = 0xd81f76c5cdeca64bb85acac6cada800772e07d0014059a5da5a0f3f584c3a365; } modifier validateToken(uint256 tokenId) { require(tokenId <= IERC721Enumerable(_hashquestsContract).totalSupply(), "Invalid NFT ID."); require(verifyNFTOwnership(msg.sender, tokenId), "Sender must be the owner of the NFT passed as the argument."); _; } modifier ongoingQuest(uint256 tokenId) { uint8 questId = getQuestId(tokenId); require(!prizeWinners[questId].prizeClaimed, "This quest is completed."); _; } /** * @dev Changes the BLOCK_DELAY to value > MIN_BLOCK_DELAY. * Meant to allow for increasing the block delay in case of clogged transactions. */ function changeBlockDelay(uint8 newBlockDelay) onlyOwner public { require(newBlockDelay >= MIN_BLOCK_DELAY, "Block delay can't be smaller than the MIN_BLOCK_DELAY."); BLOCK_DELAY = newBlockDelay; } /** * @dev Payable method meant to fill the contract's balance. */ function fillTreasure() public override payable returns (bool) { historicalTreasure = historicalTreasure.add(msg.value); emit treasureFilled(msg.value, address(this).balance, historicalTreasure); return true; } /** * @dev Commits an answer to mitigate front running. * Hash must be a keccak256(tokenId, answer, msg.sender) */ function precommitAnswer(bytes32 hashedMessage, uint256 tokenId) public validateToken(tokenId) ongoingQuest(tokenId) { precommitRecords[msg.sender] = (Precommit({ block: block.number, commitAnswer: hashedMessage })); } /** * @dev Check for correct answer and pays the prize if correct */ function answerQuest(string memory answer, uint256 tokenId) public validateToken(tokenId) ongoingQuest(tokenId) { Precommit memory commit = precommitRecords[msg.sender]; require(block.number >= commit.block.add(BLOCK_DELAY), "Wait the block delay before submitting the answer."); // Validates commit bytes32 commitHash = keccak256(abi.encode(tokenId, answer, msg.sender)); require(commit.commitAnswer == commitHash, "Your commited answer doesn't match your current answer."); // Validates answer bytes32 answerHash = keccak256(abi.encode(answer)); uint8 questId = getQuestId(tokenId); bytes32 correctAnswer = questAnswers[questId]; if (answerHash == correctAnswer) { prizeWinners[questId] = Winner({ timestamp: block.timestamp, nftId: tokenId, paid: 0, prizeClaimed: true, answer: answer }); emit completedQuest(tokenId, answer, msg.sender, questId); // Pays the winner claimTreaure(prizeWinners[questId], questId); precommitRecords[msg.sender]; } else { revert("Incorrect answer! When changing the answer a new commit is requried"); } } /** * @dev Check is msg.sender is the owner of the tokenId */ function verifyNFTOwnership(address user, uint256 tokenId) private view returns (bool) { // Verify the ownership of NFT require(_hashquestsContract != address(0), "Owner haven't defined the Hashquests contract yet."); if (IERC721Enumerable(_hashquestsContract).ownerOf(tokenId) == user) { return true; } return false; } /** * @dev Returns the questId based on the last digit of tokenId */ function getQuestId(uint256 tokenId) private pure returns (uint8) { uint256 lastDigit = tokenId.mod(10); if (lastDigit == 0 || lastDigit == 5) { return 1; } else if (lastDigit == 1 || lastDigit == 6) { return 2; } else if (lastDigit == 2 || lastDigit == 7) { return 3; } else if (lastDigit == 3 || lastDigit == 8) { return 4; } else { return 5; } } /** * @dev Keeps track of winners shares and pays the winner. */ function claimTreaure(Winner storage winner, uint8 questId) private nonReentrant() { uint256 treasureShare = historicalTreasure.div(5); uint256 withdrawAmount = treasureShare.sub(winner.paid); require(withdrawAmount > 0, "All share of this NFTs treasure has been paid."); winner.paid = winner.paid.add(withdrawAmount); (bool success, ) = msg.sender.call{value:withdrawAmount}(""); require(success, "Treasure transfer failed."); emit winnerCollectedPrize(withdrawAmount, winner.nftId, questId, msg.sender); } /** * @dev Allows a winner to withdraw if there is residual treasure for that quest. */ function withdrawPartialReward(uint256 tokenId) public validateToken(tokenId) { uint8 questId = getQuestId(tokenId); require(prizeWinners[questId].prizeClaimed, "This quest isn't claimed yet. Use answerQuest method."); require(prizeWinners[questId].nftId == tokenId, "This NFT has no claim over the treasure."); claimTreaure(prizeWinners[questId], questId); } }
Changes the BLOCK_DELAY to value > MIN_BLOCK_DELAY. Meant to allow for increasing the block delay in case of clogged transactions./
function changeBlockDelay(uint8 newBlockDelay) onlyOwner public { require(newBlockDelay >= MIN_BLOCK_DELAY, "Block delay can't be smaller than the MIN_BLOCK_DELAY."); BLOCK_DELAY = newBlockDelay; }
7,989,917
./partial_match/100/0x81A194828e3c8e3ac91668E93A8A202dF505ACBa/sources/PriceBettingT1S2.sol
(uint80 roundID, int256 int256, , , ) = price = uint256(AggregatorEthereumV3().latestRoundData); console.log("roundID: %s, price: %s", roundID, price);
function getLatestPrice() public view returns (uint256) { return uint256( AggregatorXDAI(addrPriceFeed).latestAnswer() ); }
16,649,822
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin\upgrades\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts\interfaces\defi\IDefiProtocol.sol pragma solidity ^0.5.12; interface IDefiProtocol { /** * @notice Transfer tokens from sender to DeFi protocol * @param token Address of token * @param amount Value of token to deposit * @return new balances of each token */ function handleDeposit(address token, uint256 amount) external; function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external; /** * @notice Transfer tokens from DeFi protocol to beneficiary * @param token Address of token * @param amount Denormalized value of token to withdraw * @return new balances of each token */ function withdraw(address beneficiary, address token, uint256 amount) external; /** * @notice Transfer tokens from DeFi protocol to beneficiary * @param amounts Array of amounts to withdraw, in order of supportedTokens() * @return new balances of each token */ function withdraw(address beneficiary, uint256[] calldata amounts) external; /** * @notice Claim rewards. Reward tokens will be stored on protocol balance. * @return tokens and their amounts received */ function claimRewards() external returns(address[] memory tokens, uint256[] memory amounts); /** * @notice Withdraw reward tokens to user * @dev called by SavingsModule * @param token Reward token to withdraw * @param user Who should receive tokens * @param amount How many tokens to send */ function withdrawReward(address token, address user, uint256 amount) external; /** * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes */ function balanceOf(address token) external returns(uint256); /** * @notice Balance of all tokens supported by protocol * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes */ function balanceOfAll() external returns(uint256[] memory); /** * @notice Returns normalized (to USD with 18 decimals) summary balance * of pool using all tokens in this protocol */ function normalizedBalance() external returns(uint256); function supportedTokens() external view returns(address[] memory); function supportedTokensCount() external view returns(uint256); function supportedRewardTokens() external view returns(address[] memory); function isSupportedRewardToken(address token) external view returns(bool); /** * @notice Returns if this protocol can swap all it's normalizedBalance() to specified token */ function canSwapToToken(address token) external view returns(bool); } // File: contracts\interfaces\defi\ICurveFiDeposit.sol pragma solidity ^0.5.12; contract ICurveFiDeposit { function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount) external; function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust) external; function withdraw_donated_dust() external; function coins(int128 i) external view returns (address); function underlying_coins (int128 i) external view returns (address); function curve() external view returns (address); function token() external view returns (address); function calc_withdraw_one_coin (uint256 _token_amount, int128 i) external view returns (uint256); } // File: contracts\interfaces\defi\ICurveFiSwap.sol pragma solidity ^0.5.12; interface ICurveFiSwap { function balances(int128 i) external view returns(uint256); function A() external view returns(uint256); function fee() external view returns(uint256); function coins(int128 i) external view returns (address); } // File: contracts\interfaces\defi\ICurveFiLiquidityGauge.sol pragma solidity ^0.5.16; interface ICurveFiLiquidityGauge { //Addresses of tokens function lp_token() external returns(address); function crv_token() external returns(address); //Work with LP tokens function balanceOf(address addr) external view returns (uint256); function deposit(uint256 _value) external; function withdraw(uint256 _value) external; //Work with CRV function claimable_tokens(address addr) external returns (uint256); function minter() external view returns(address); //use minter().mint(gauge_addr) to claim CRV } // File: contracts\interfaces\defi\ICurveFiMinter.sol pragma solidity ^0.5.16; interface ICurveFiMinter { function mint(address gauge_addr) external; } // File: contracts\interfaces\defi\ICErc20.sol pragma solidity ^0.5.12; /** * Most important functions of Compound CErc20 token. * Source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol * * Original interface name: CErc20Interface * but we use our naming covention. */ //solhint-disable func-order contract ICErc20 { /*** User Interface of CTokenInterface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function accrueInterest() external returns (uint256); /*** User Interface of CErc20Interface ***/ function mint(uint mintAmount) external returns (uint256); function redeem(uint redeemTokens) external returns (uint256); function redeemUnderlying(uint redeemAmount) external returns (uint256); } // File: contracts\interfaces\defi\IComptroller.sol pragma solidity ^0.5.16; interface IComptroller { function claimComp(address holder) external; function claimComp(address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers) external; function getCompAddress() external view returns (address); } // File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts\common\Base.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Base is Initializable, Context, Ownable { address constant ZERO_ADDRESS = address(0); function initialize() public initializer { Ownable.initialize(_msgSender()); } } // File: contracts\core\ModuleNames.sol pragma solidity ^0.5.12; /** * @dev List of module names */ contract ModuleNames { // Pool Modules string internal constant MODULE_ACCESS = "access"; string internal constant MODULE_SAVINGS = "savings"; string internal constant MODULE_INVESTING = "investing"; string internal constant MODULE_STAKING = "staking"; string internal constant MODULE_DCA = "dca"; // External Modules (used to store addresses of external contracts) string internal constant CONTRACT_RAY = "ray"; } // File: contracts\common\Module.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Module is Base, ModuleNames { event PoolAddressChanged(address newPool); address public pool; function initialize(address _pool) public initializer { Base.initialize(); setPool(_pool); } function setPool(address _pool) public onlyOwner { require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero"); pool = _pool; emit PoolAddressChanged(_pool); } function getModuleAddress(string memory module) public view returns(address){ require(pool != ZERO_ADDRESS, "Module: no pool"); (bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module)); //Forward error from Pool contract if (!success) assembly { revert(add(result, 32), result) } address moduleAddress = abi.decode(result, (address)); // string memory error = string(abi.encodePacked("Module: requested module not found - ", module)); // require(moduleAddress != ZERO_ADDRESS, error); require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress; } } // File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts\modules\defi\DefiOperatorRole.sol pragma solidity ^0.5.12; contract DefiOperatorRole is Initializable, Context { using Roles for Roles.Role; event DefiOperatorAdded(address indexed account); event DefiOperatorRemoved(address indexed account); Roles.Role private _operators; function initialize(address sender) public initializer { if (!isDefiOperator(sender)) { _addDefiOperator(sender); } } modifier onlyDefiOperator() { require(isDefiOperator(_msgSender()), "DefiOperatorRole: caller does not have the DefiOperator role"); _; } function addDefiOperator(address account) public onlyDefiOperator { _addDefiOperator(account); } function renounceDefiOperator() public { _removeDefiOperator(_msgSender()); } function isDefiOperator(address account) public view returns (bool) { return _operators.has(account); } function _addDefiOperator(address account) internal { _operators.add(account); emit DefiOperatorAdded(account); } function _removeDefiOperator(address account) internal { _operators.remove(account); emit DefiOperatorRemoved(account); } } // File: contracts\modules\defi\ProtocolBase.sol pragma solidity ^0.5.12; contract ProtocolBase is Module, DefiOperatorRole, IDefiProtocol { uint256 constant MAX_UINT256 = uint256(-1); event RewardTokenClaimed(address indexed token, uint256 amount); using SafeMath for uint256; using SafeERC20 for IERC20; mapping(address=>uint256) public rewardBalances; //Mapping of already claimed amounts of reward tokens function initialize(address _pool) public initializer { Module.initialize(_pool); DefiOperatorRole.initialize(_msgSender()); } function upgrade(address rtkn, uint256 newStoredBalance) public onlyOwner { require(rewardBalances[rtkn] == 0, "No upgrade required"); uint256 balance = IERC20(rtkn).balanceOf(address(this)); require(newStoredBalance <= balance, "Can not store more than available"); rewardBalances[rtkn] = newStoredBalance; } function supportedRewardTokens() public view returns(address[] memory); function isSupportedRewardToken(address token) public view returns(bool); function cliamRewardsFromProtocol() internal; function claimRewards() public onlyDefiOperator returns(address[] memory tokens, uint256[] memory amounts){ cliamRewardsFromProtocol(); // Check what we received address[] memory rewardTokens = supportedRewardTokens(); uint256[] memory rewardAmounts = new uint256[](rewardTokens.length); uint256 receivedRewardTokensCount; for(uint256 i = 0; i < rewardTokens.length; i++) { address rtkn = rewardTokens[i]; uint256 newBalance = IERC20(rtkn).balanceOf(address(this)); if(newBalance > rewardBalances[rtkn]) { receivedRewardTokensCount++; rewardAmounts[i] = newBalance.sub(rewardBalances[rtkn]); rewardBalances[rtkn] = newBalance; } } //Fill result arrays tokens = new address[](receivedRewardTokensCount); amounts = new uint256[](receivedRewardTokensCount); if(receivedRewardTokensCount > 0) { uint256 j; for(uint256 i = 0; i < rewardTokens.length; i++) { if(rewardAmounts[i] > 0) { tokens[j] = rewardTokens[i]; amounts[j] = rewardAmounts[i]; j++; } } } } function withdrawReward(address token, address user, uint256 amount) public onlyDefiOperator { require(isSupportedRewardToken(token), "ProtocolBase: not reward token"); rewardBalances[token] = rewardBalances[token].sub(amount); IERC20(token).safeTransfer(user, amount); } } // File: contracts\modules\defi\CurveFiProtocol.sol pragma solidity ^0.5.12; contract CurveFiProtocol is ProtocolBase { // Withdrawing one token form Curve.fi pool may lead to small amount of pool token may left unused on Deposit contract. // If DONATE_DUST = true, it will be left there and donated to curve.fi, otherwise we will use gas to transfer it back. bool public constant DONATE_DUST = false; uint256 constant MAX_UINT256 = uint256(-1); using SafeMath for uint256; using SafeERC20 for IERC20; event CurveFiSetup(address swap, address deposit, address liquidityGauge); event TokenRegistered(address indexed token); event TokenUnregistered(address indexed token); ICurveFiSwap public curveFiSwap; ICurveFiDeposit public curveFiDeposit; ICurveFiLiquidityGauge public curveFiLPGauge; ICurveFiMinter public curveFiMinter; IERC20 public curveFiToken; address public crvToken; address[] internal _registeredTokens; uint256 public slippageMultiplier; //Multiplier to work-around slippage & fees when witharawing one token mapping(address => uint8) public decimals; function nCoins() internal returns(uint256); function deposit_add_liquidity(uint256[] memory amounts, uint256 min_mint_amount) internal; function deposit_remove_liquidity_imbalance(uint256[] memory amounts, uint256 max_burn_amount) internal; function initialize(address _pool) public initializer { ProtocolBase.initialize(_pool); _registeredTokens = new address[](nCoins()); slippageMultiplier = 1.01*1e18; //Max slippage - 1%, if more - tx will fail } function setCurveFi(address deposit, address liquidityGauge) public onlyDefiOperator { if (address(curveFiDeposit) != address(0)) { //We need to unregister tokens first for (uint256 i=0; i < _registeredTokens.length; i++){ if (_registeredTokens[i] != address(0)) { _unregisterToken(_registeredTokens[i]); _registeredTokens[i] = address(0); } } } curveFiDeposit = ICurveFiDeposit(deposit); curveFiSwap = ICurveFiSwap(curveFiDeposit.curve()); curveFiToken = IERC20(curveFiDeposit.token()); curveFiLPGauge = ICurveFiLiquidityGauge(liquidityGauge); curveFiMinter = ICurveFiMinter(curveFiLPGauge.minter()); address lpToken = curveFiLPGauge.lp_token(); require(lpToken == address(curveFiToken), "CurveFiProtocol: LP tokens do not match"); crvToken = curveFiLPGauge.crv_token(); IERC20(curveFiToken).safeApprove(address(curveFiDeposit), MAX_UINT256); IERC20(curveFiToken).safeApprove(address(curveFiLPGauge), MAX_UINT256); for (uint256 i=0; i < _registeredTokens.length; i++){ address token = curveFiDeposit.underlying_coins(int128(i)); _registeredTokens[i] = token; _registerToken(token); IERC20(token).safeApprove(address(curveFiDeposit), MAX_UINT256); } emit CurveFiSetup(address(curveFiSwap), address(curveFiDeposit), address(curveFiLPGauge)); } function setSlippageMultiplier(uint256 _slippageMultiplier) public onlyDefiOperator { require(_slippageMultiplier >= 1e18, "CurveFiYModule: multiplier should be > 1"); slippageMultiplier = _slippageMultiplier; } function handleDeposit(address token, uint256 amount) public onlyDefiOperator { uint256[] memory amounts = new uint256[](nCoins()); for (uint256 i=0; i < _registeredTokens.length; i++){ amounts[i] = IERC20(_registeredTokens[i]).balanceOf(address(this)); // Check balance which is left after previous withdrawal //amounts[i] = (_registeredTokens[i] == token)?amount:0; if (_registeredTokens[i] == token) { require(amounts[i] >= amount, "CurveFiYProtocol: requested amount is not deposited"); } } deposit_add_liquidity(amounts, 0); stakeCurveFiToken(); } function handleDeposit(address[] memory tokens, uint256[] memory amounts) public onlyDefiOperator { require(tokens.length == amounts.length, "CurveFiYProtocol: count of tokens does not match count of amounts"); require(amounts.length == nCoins(), "CurveFiYProtocol: amounts count does not match registered tokens"); uint256[] memory amnts = new uint256[](nCoins()); for (uint256 i=0; i < _registeredTokens.length; i++){ uint256 idx = getTokenIndex(tokens[i]); amnts[idx] = IERC20(_registeredTokens[idx]).balanceOf(address(this)); // Check balance which is left after previous withdrawal require(amnts[idx] >= amounts[i], "CurveFiYProtocol: requested amount is not deposited"); } deposit_add_liquidity(amnts, 0); stakeCurveFiToken(); } /** * @dev With this function beneficiary will recieve exact amount he asked. * Slippage + fee is paid from his account in SavingsModule */ function withdraw(address beneficiary, address token, uint256 amount) public onlyDefiOperator { uint256 tokenIdx = getTokenIndex(token); uint256 available = IERC20(token).balanceOf(address(this)); uint256 wAmount = amount.sub(available); //Count tokens left after previous withdrawal // count shares for proportional withdraw uint256 nAmount = normalizeAmount(token, wAmount); uint256 nBalance = normalizedBalance(); uint256 poolShares = curveFiTokenBalance(); uint256 withdrawShares = poolShares.mul(nAmount).mul(slippageMultiplier).div(nBalance).div(1e18); //Increase required amount to some percent, so that we definitely have enough to withdraw unstakeCurveFiToken(withdrawShares); curveFiDeposit.remove_liquidity_one_coin(withdrawShares, int128(tokenIdx), wAmount, DONATE_DUST); available = IERC20(token).balanceOf(address(this)); require(available >= amount, "CurveFiYProtocol: failed to withdraw required amount"); IERC20 ltoken = IERC20(token); ltoken.safeTransfer(beneficiary, amount); } function withdraw(address beneficiary, uint256[] memory amounts) public onlyDefiOperator { require(amounts.length == nCoins(), "CurveFiYProtocol: wrong amounts array length"); uint256 nWithdraw; uint256[] memory amnts = new uint256[](nCoins()); uint256 i; for (i = 0; i < _registeredTokens.length; i++){ address tkn = _registeredTokens[i]; uint256 available = IERC20(tkn).balanceOf(address(this)); if(available < amounts[i]){ amnts[i] = amounts[i].sub(available); }else{ amnts[i] = 0; } nWithdraw = nWithdraw.add(normalizeAmount(tkn, amnts[i])); } uint256 nBalance = normalizedBalance(); uint256 poolShares = curveFiTokenBalance(); uint256 withdrawShares = poolShares.mul(nWithdraw).mul(slippageMultiplier).div(nBalance).div(1e18); //Increase required amount to some percent, so that we definitely have enough to withdraw unstakeCurveFiToken(withdrawShares); deposit_remove_liquidity_imbalance(amnts, withdrawShares); for (i = 0; i < _registeredTokens.length; i++){ IERC20 ltoken = IERC20(_registeredTokens[i]); ltoken.safeTransfer(beneficiary, amounts[i]); } } function supportedRewardTokens() public view returns(address[] memory) { address[] memory rtokens = new address[](1); rtokens[0] = crvToken; return rtokens; } function isSupportedRewardToken(address token) public view returns(bool) { return(token == crvToken); } function cliamRewardsFromProtocol() internal { curveFiMinter.mint(address(curveFiLPGauge)); } function balanceOf(address token) public returns(uint256) { uint256 tokenIdx = getTokenIndex(token); uint256 cfBalance = curveFiTokenBalance(); uint256 cfTotalSupply = curveFiToken.totalSupply(); uint256 tokenCurveFiBalance = curveFiSwap.balances(int128(tokenIdx)); return tokenCurveFiBalance.mul(cfBalance).div(cfTotalSupply); } function balanceOfAll() public returns(uint256[] memory balances) { IERC20 cfToken = IERC20(curveFiDeposit.token()); uint256 cfBalance = curveFiTokenBalance(); uint256 cfTotalSupply = cfToken.totalSupply(); balances = new uint256[](_registeredTokens.length); for (uint256 i=0; i < _registeredTokens.length; i++){ uint256 tcfBalance = curveFiSwap.balances(int128(i)); balances[i] = tcfBalance.mul(cfBalance).div(cfTotalSupply); } } function normalizedBalance() public returns(uint256) { uint256[] memory balances = balanceOfAll(); uint256 summ; for (uint256 i=0; i < _registeredTokens.length; i++){ summ = summ.add(normalizeAmount(_registeredTokens[i], balances[i])); } return summ; } function supportedTokens() public view returns(address[] memory){ return _registeredTokens; } function supportedTokensCount() public view returns(uint256) { return _registeredTokens.length; } function getTokenIndex(address token) public view returns(uint256) { for (uint256 i=0; i < _registeredTokens.length; i++){ if (_registeredTokens[i] == token){ return i; } } revert("CurveFiYProtocol: token not registered"); } function canSwapToToken(address token) public view returns(bool) { for (uint256 i=0; i < _registeredTokens.length; i++){ if (_registeredTokens[i] == token){ return true; } } return false; } function normalizeAmount(address token, uint256 amount) internal view returns(uint256) { uint256 _decimals = uint256(decimals[token]); if (_decimals == 18) { return amount; } else if (_decimals > 18) { return amount.div(10**(_decimals-18)); } else if (_decimals < 18) { return amount.mul(10**(18-_decimals)); } } function denormalizeAmount(address token, uint256 amount) internal view returns(uint256) { uint256 _decimals = uint256(decimals[token]); if (_decimals == 18) { return amount; } else if (_decimals > 18) { return amount.mul(10**(_decimals-18)); } else if (_decimals < 18) { return amount.div(10**(18-_decimals)); } } function curveFiTokenBalance() internal view returns(uint256) { uint256 notStaked = curveFiToken.balanceOf(address(this)); uint256 staked = curveFiLPGauge.balanceOf(address(this)); return notStaked.add(staked); } function stakeCurveFiToken() internal { uint256 cftBalance = curveFiToken.balanceOf(address(this)); curveFiLPGauge.deposit(cftBalance); } function unstakeCurveFiToken(uint256 amount) internal { curveFiLPGauge.withdraw(amount); } function _registerToken(address token) private { IERC20 ltoken = IERC20(token); uint256 currentBalance = ltoken.balanceOf(address(this)); if (currentBalance > 0) { handleDeposit(token, currentBalance); } decimals[token] = ERC20Detailed(token).decimals(); emit TokenRegistered(token); } function _unregisterToken(address token) private { uint256 balance = IERC20(token).balanceOf(address(this)); //TODO: ensure there is no interest on this token which is wating to be withdrawn if (balance > 0){ withdraw(token, _msgSender(), balance); //This updates withdrawalsSinceLastDistribution } emit TokenUnregistered(token); } uint256[50] private ______gap; } // File: contracts\interfaces\defi\ICurveFiDeposit_Y.sol pragma solidity ^0.5.12; contract ICurveFiDeposit_Y { function add_liquidity (uint256[4] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity (uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance (uint256[4] calldata uamounts, uint256 max_burn_amount) external; } // File: contracts\interfaces\defi\IYErc20.sol pragma solidity ^0.5.12; //solhint-disable func-order contract IYErc20 { //ERC20 functions function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, 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); //yToken functions function deposit(uint256 amount) external; function withdraw(uint256 shares) external; function getPricePerFullShare() external view returns (uint256); function token() external returns(address); } // File: contracts\modules\defi\CurveFiProtocol_Y.sol pragma solidity ^0.5.12; contract CurveFiProtocol_Y is CurveFiProtocol { uint256 private constant N_COINS = 4; function nCoins() internal returns(uint256) { return N_COINS; } function convertArray(uint256[] memory amounts) internal pure returns(uint256[N_COINS] memory) { require(amounts.length == N_COINS, "CurveFiProtocol_Y: wrong token count"); uint256[N_COINS] memory amnts = [uint256(0), uint256(0), uint256(0), uint256(0)]; for(uint256 i=0; i < N_COINS; i++){ amnts[i] = amounts[i]; } return amnts; } function deposit_add_liquidity(uint256[] memory amounts, uint256 min_mint_amount) internal { ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), min_mint_amount); } function deposit_remove_liquidity_imbalance(uint256[] memory amounts, uint256 max_burn_amount) internal { ICurveFiDeposit_Y(address(curveFiDeposit)).remove_liquidity_imbalance(convertArray(amounts), max_burn_amount); } function balanceOf(address token) public returns(uint256) { uint256 tokenIdx = getTokenIndex(token); uint256 cfBalance = curveFiTokenBalance(); uint256 cfTotalSupply = curveFiToken.totalSupply(); uint256 yTokenCurveFiBalance = curveFiSwap.balances(int128(tokenIdx)); uint256 yTokenShares = yTokenCurveFiBalance.mul(cfBalance).div(cfTotalSupply); IYErc20 yToken = IYErc20(curveFiDeposit.coins(int128(tokenIdx))); uint256 tokenBalance = yToken.getPricePerFullShare().mul(yTokenShares).div(1e18); //getPricePerFullShare() returns balance of underlying token multiplied by 1e18 return tokenBalance; } function balanceOfAll() public returns(uint256[] memory balances) { IERC20 cfToken = IERC20(curveFiDeposit.token()); uint256 cfBalance = curveFiTokenBalance(); uint256 cfTotalSupply = cfToken.totalSupply(); balances = new uint256[](_registeredTokens.length); for (uint256 i=0; i < _registeredTokens.length; i++){ uint256 ycfBalance = curveFiSwap.balances(int128(i)); uint256 yShares = ycfBalance.mul(cfBalance).div(cfTotalSupply); IYErc20 yToken = IYErc20(curveFiDeposit.coins(int128(i))); balances[i] = yToken.getPricePerFullShare().mul(yShares).div(1e18); //getPricePerFullShare() returns balance of underlying token multiplied by 1e18 } } }
We need to unregister tokens first
function setCurveFi(address deposit, address liquidityGauge) public onlyDefiOperator { if (address(curveFiDeposit) != address(0)) { for (uint256 i=0; i < _registeredTokens.length; i++){ if (_registeredTokens[i] != address(0)) { _unregisterToken(_registeredTokens[i]); _registeredTokens[i] = address(0); } } } curveFiDeposit = ICurveFiDeposit(deposit); curveFiSwap = ICurveFiSwap(curveFiDeposit.curve()); curveFiToken = IERC20(curveFiDeposit.token()); curveFiLPGauge = ICurveFiLiquidityGauge(liquidityGauge); curveFiMinter = ICurveFiMinter(curveFiLPGauge.minter()); address lpToken = curveFiLPGauge.lp_token(); require(lpToken == address(curveFiToken), "CurveFiProtocol: LP tokens do not match"); crvToken = curveFiLPGauge.crv_token(); IERC20(curveFiToken).safeApprove(address(curveFiDeposit), MAX_UINT256); IERC20(curveFiToken).safeApprove(address(curveFiLPGauge), MAX_UINT256); for (uint256 i=0; i < _registeredTokens.length; i++){ address token = curveFiDeposit.underlying_coins(int128(i)); _registeredTokens[i] = token; _registerToken(token); IERC20(token).safeApprove(address(curveFiDeposit), MAX_UINT256); } emit CurveFiSetup(address(curveFiSwap), address(curveFiDeposit), address(curveFiLPGauge)); }
6,960,272
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./Cryptomedia.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; /** * @title Cryptomedia Factory * @author neuroswish * * Factory for deploying cryptomedia * * Good morning * Look at the valedictorian * Scared of the future while I hop in the DeLorean * */ contract CryptomediaFactory { // ======== Storage ======== address public logic; address public bondingCurve; // ======== Events ======== event CryptomediaDeployed( address contractAddress, address indexed creator, string metadataURI, string name, string symbol, uint256 reservedTokens, address bondingCurve ); // ======== Constructor ======== constructor(address _bondingCurve) { bondingCurve = _bondingCurve; Cryptomedia _cryptomediaLogic = new Cryptomedia(); _cryptomediaLogic.initialize( address(this), "Verse", "VERSE", "", bondingCurve, 0 ); logic = address(_cryptomediaLogic); } // ======== Deploy contract ======== function createCryptomedia( string calldata _tokenName, string calldata _tokenSymbol, string calldata _metadataURI, uint256 _reservedTokens ) external returns (address cryptomedia) { require( bytes(_metadataURI).length != 0, "Cryptomedia: metadata URI must be non-empty" ); cryptomedia = Clones.clone(logic); Cryptomedia(cryptomedia).initialize( msg.sender, _tokenName, _tokenSymbol, _metadataURI, bondingCurve, _reservedTokens ); emit CryptomediaDeployed( cryptomedia, msg.sender, _metadataURI, _tokenName, _tokenSymbol, _reservedTokens, bondingCurve ); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./BondingCurve.sol"; import "./interfaces/IBondingCurve.sol"; /** * @title Cryptomedia * @author neuroswish * * Cryptomedia * * I just needed time alone with my own thoughts * Got treasures in my mind, but couldn't open up my own vault * */ contract Cryptomedia is ReentrancyGuard, Initializable { // ======== Interface addresses ======== address public factory; // factory address address public bondingCurve; // bonding curve interface address // ======== Continuous token params ======== address public creator; // cryptomedia creator string public name; // cryptomedia name string public symbol; // cryptomedia symbol string public metadataURI; // cryptomedia metadata URI uint32 public reserveRatio; // reserve ratio in ppm uint32 public ppm; // token units uint256 public poolBalance; // ETH balance in contract pool uint256 public totalSupply; // total supply of tokens in circulation mapping(address => uint256) public balanceOf; // mapping of an address to that user's total token balance mapping(address => mapping(address => uint256)) public allowance; // transfer allowance // ======== Events ======== event Buy( address indexed buyer, uint256 poolBalance, uint256 totalSupply, uint256 tokens, uint256 price ); event Sell( address indexed seller, uint256 poolBalance, uint256 totalSupply, uint256 tokens, uint256 eth ); event MetadataUpdated(string metadataURI); // ERC-20 event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); // ======== Modifiers ======== /** * @notice Check to see if address holds tokens */ modifier holder() { require(balanceOf[msg.sender] > 0, "Must hold tokens"); _; } /** * @notice Check to see if address holds tokens */ modifier onlyCreator() { require(msg.sender == creator, "Must be creator"); _; } // ======== Initializer for new market proxy ======== /** * @notice Initialize a new market * @dev Sets reserveRatio, ppm, fee, name, and bondingCurve address; called by factory at time of deployment */ function initialize( address _creator, string calldata _name, string calldata _symbol, string calldata _metadataURI, address _bondingCurve, uint256 _reservedTokens ) external initializer { reserveRatio = 333333; ppm = 1000000; name = _name; symbol = _symbol; bondingCurve = _bondingCurve; creator = _creator; metadataURI = _metadataURI; // creator can specify a number of tokens to reserve upon supply initialization _mint(creator, _reservedTokens); } // ======== Functions ======== /** * @notice Buy market tokens with ETH * @dev Emits a Buy event upon success; callable by anyone */ function buy(uint256 _price, uint256 _minTokensReturned) external payable { require(msg.value == _price && msg.value > 0, "Invalid price"); require(_minTokensReturned > 0, "Invalid slippage"); // calculate tokens returned uint256 tokensReturned; if (totalSupply == 0 || poolBalance == 0) { tokensReturned = IBondingCurve(bondingCurve) .calculateInitializationReturn(_price, reserveRatio); } else { tokensReturned = IBondingCurve(bondingCurve) .calculatePurchaseReturn( totalSupply, poolBalance, reserveRatio, _price ); } require(tokensReturned >= _minTokensReturned, "Slippage"); // mint tokens for buyer _mint(msg.sender, tokensReturned); poolBalance += _price; emit Buy(msg.sender, poolBalance, totalSupply, tokensReturned, _price); } /** * @notice Sell market tokens for ETH * @dev Emits a Sell event upon success; callable by token holders */ function sell(uint256 _tokens, uint256 _minETHReturned) external holder nonReentrant { require( _tokens > 0 && _tokens <= balanceOf[msg.sender], "Invalid token amount" ); require(poolBalance > 0, "Insufficient pool balance"); require(_minETHReturned > 0, "Invalid slippage"); // calculate ETH returned uint256 ethReturned = IBondingCurve(bondingCurve).calculateSaleReturn( totalSupply, poolBalance, reserveRatio, _tokens ); require(ethReturned >= _minETHReturned, "Slippage"); // burn tokens _burn(msg.sender, _tokens); poolBalance -= ethReturned; sendValue(payable(msg.sender), ethReturned); emit Sell(msg.sender, poolBalance, totalSupply, _tokens, ethReturned); } // ============ Metadata ============ /** * @notice Enable creator to update the cryptomedia URI * @dev Only callable by creator */ function updateMetadataURI(string memory _metadataURI) public onlyCreator { metadataURI = _metadataURI; } // ============ Utility ============ /** * @notice Send ETH in a safe manner * @dev Prevents reentrancy, emits a Transfer event upon success */ function sendValue(address recipient, uint256 amount) internal { require(address(this).balance >= amount, "Invalid amount"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = payable(recipient).call{value: amount}("Reverted"); require( success, "Address: unable to send value, recipient may have reverted" ); } // ============ ERC-20 ============ /** * @notice Mints tokens * @dev Emits a Transfer event upon success */ function _mint(address _to, uint256 _value) internal { totalSupply += _value; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } /** * @notice Burns tokens * @dev Emits a Transfer event upon success */ function _burn(address _from, uint256 _value) internal { balanceOf[_from] -= _value; totalSupply -= _value; emit Transfer(_from, address(0), _value); } /** * @notice Approve token allowance * @dev Emits an Approval event upon success */ function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Transfer tokens * @dev Emits a Transfer event upon success */ function _transfer( address from, address to, uint256 value ) private { balanceOf[from] -= value; balanceOf[to] += value; emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = allowance[sender][msg.sender]; require( currentAllowance >= amount, "Transfer amount exceeds allowance" ); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // 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; /** * @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: GPL-3.0-or-later pragma solidity ^0.8.4; /** * @title Bonding Curve * @author neuroswish * * Bonding curve functions managing the purchase and sale of continuous tokens * * Listen to the kids, bro * */ import "./Power.sol"; contract BondingCurve is Power { uint32 public constant maxRatio = 1000000; uint256 public constant slopeFactor = 100000; /** * @dev given total supply, pool balance, reserve ratio and a price, calculates the number of tokens returned * * Formula: * return = _supply * ((1 + _price / _poolBalance) ^ (_reserveRatio / maxRatio) - 1) * * @param _supply liquid token supply * @param _poolBalance pool balance * @param _reserveRatio reserve weight, represented in ppm (1-1000000) * @param _price ETH * * @return tokens */ function calculatePurchaseReturn( uint256 _supply, uint256 _poolBalance, uint32 _reserveRatio, uint256 _price ) public view returns (uint256) { // validate input require(_supply > 0, "INVALID SUPPLY"); require(_poolBalance > 0, "INVALID POOL BALANCE"); // calculate result (uint256 result, uint8 precision) = power( (_price + _poolBalance), _poolBalance, _reserveRatio, maxRatio ); uint256 temp = (_supply * result) >> precision; return (temp - _supply); } /** * @dev given total supply, pool balance, reserve ratio and desired number of tokens, calculates the price required * * Formula: * return = _poolBalance * ((1 + _tokens / _supply) ^ (maxRatio / reserveRatio) - 1) * * @param _supply liquid token supply * @param _poolBalance reserve balance * @param _reserveRatio reserve weight, represented in ppm (1-1000000) * @param _tokens amount of reserve tokens to get the target amount for * * @return ETH */ function calculatePrice( uint256 _supply, uint256 _poolBalance, uint32 _reserveRatio, uint256 _tokens ) public view returns (uint256) { (uint256 result, uint8 precision) = power( (_tokens + _supply), _supply, maxRatio, _reserveRatio ); uint256 temp = (_poolBalance * result) >> precision; return (temp - _poolBalance); } /** * @dev given total supply, pool balance, reserve ratio and a token amount, calculates the amount of ETH returned * * Formula: * return = _poolBalance * (1 - (1 - _tokens / _supply) ^ (maxRatio / _reserveRatio)) * * @param _supply liquid token supply * @param _poolBalance reserve balance * @param _reserveRatio reserve weight, represented in ppm (1-1000000) * @param _tokens amount of liquid tokens to get the target amount for * * @return ETH */ function calculateSaleReturn( uint256 _supply, uint256 _poolBalance, uint32 _reserveRatio, uint256 _tokens ) public view returns (uint256) { // validate input require(_supply > 0, "INVALID SUPPLY"); require(_poolBalance > 0, "INVALID SUPPLY"); // edge case for selling entire supply if (_tokens == _supply) { return _poolBalance; } (uint256 result, uint8 precision) = power( _supply, (_supply - _tokens), maxRatio, _reserveRatio ); return ((_poolBalance * result) - (_poolBalance << precision)) / result; } /** * @dev given a price, reserve ratio, and slope factor, calculates the number of tokens returned when initializing the bonding curve supply * * Formula: * return = (_price / (_reserveRatio * _slopeFactor)) ** _reserveRatio * * @param _price liquid token supply * @param _reserveRatio reserve weight, represented in ppm (1-1000000) * * @return initial token amount */ function calculateInitializationReturn(uint256 _price, uint32 _reserveRatio) public view returns (uint256) { if (_reserveRatio == maxRatio) { return (_price * slopeFactor); } (uint256 temp, uint256 precision) = powerInitial( (_price * slopeFactor), _reserveRatio, maxRatio, _reserveRatio, maxRatio ); return (temp >> precision); } /** * @dev given a reserve ratio and slope factor, calculates the number of price required to purchase the first token when initializing the bonding curve supply * * Formula: * price = (_reserveRatio * slopeFactor) / maxRatio * * @param _reserveRatio reserve weight, represented in ppm (1-1000000) * * @return initial token price */ function calculateInitializationPrice(uint32 _reserveRatio) public pure returns (uint256) { if (_reserveRatio == maxRatio) { return (slopeFactor); } return ((_reserveRatio * slopeFactor) / maxRatio); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; interface IBondingCurve { function calculateInitializationReturn(uint256 _price, uint32 _reserveRatio) external view returns (uint256); function calculateInitializationPrice(uint32 _reserveRatio) external pure returns (uint256); function calculatePurchaseReturn( uint256 _supply, uint256 _poolBalance, uint32 _reserveRatio, uint256 _price ) external returns (uint256); function calculatePrice( uint256 _supply, uint256 _poolBalance, uint32 _reserveRatio, uint256 _tokens ) external returns (uint256); function calculateSaleReturn( uint256 _supply, uint256 _poolBalance, uint32 _reserveRatio, uint256 _tokens ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /** * @title Power * * Functions to calculate fractional exponents * * Four in the mornin', and I'm zonin' * They say I'm possessed, it's an omen * */ contract Power { uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; uint256[128] private maxExpArray; function initMaxExpArray() public { maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } constructor() { initMaxExpArray(); } /** * @dev General Description: * Determine a value of precision. * Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. * Return the result along with the precision used. * * Detailed Description: * Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". * The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". * The larger "precision" is, the more accurately this value represents the real value. * However, the larger "precision" is, the more bits are required in order to store this value. * And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). * This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". * Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. * This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. * This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". * Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD". */ function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD ) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = (_baseN * FIXED_1) / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = (baseLog * _expN) / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return ( generalExp( baseLogTimesExp >> (MAX_PRECISION - precision), precision ), precision ); } } function powerInitial( uint256 _baseN, uint256 _baseDNumerator, uint256 _baseDDenominator, uint32 _expN, uint32 _expD ) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = (_baseN * _baseDDenominator * FIXED_1) / (_baseDNumerator); if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = (baseLog * _expN) / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return ( generalExp( baseLogTimesExp >> (MAX_PRECISION - precision), precision ), precision ); } } /** * @dev computes log(x / FIXED_1) * FIXED_1. * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return (res * LN2_NUMERATOR) / LN2_DENOMINATOR; } /** * @dev computes the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** * @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: * - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] * - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8 result) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) { result = hi; return result; } if (maxExpArray[lo] >= _x) { result = lo; return result; } require(false); } /** * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". * it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. * the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". * the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** * @dev computes log(x / FIXED_1) * FIXED_1 * Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1 * Auto-generated via 'PrintFunctionOptimalLog.py' * Detailed description: * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 * - The natural logarithm of the input is calculated by summing up the intermediate results above * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) { res += 0x40000000000000000000000000000000; x = (x * FIXED_1) / 0xd3094c70f034de4b96ff7d5b6f99fcd8; } // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) { res += 0x20000000000000000000000000000000; x = (x * FIXED_1) / 0xa45af1e1f40c333b3de1db4dd55f29a7; } // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) { res += 0x10000000000000000000000000000000; x = (x * FIXED_1) / 0x910b022db7ae67ce76b441c27035c6a1; } // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) { res += 0x08000000000000000000000000000000; x = (x * FIXED_1) / 0x88415abbe9a76bead8d00cf112e4d4a8; } // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) { res += 0x04000000000000000000000000000000; x = (x * FIXED_1) / 0x84102b00893f64c705e841d5d4064bd3; } // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) { res += 0x02000000000000000000000000000000; x = (x * FIXED_1) / 0x8204055aaef1c8bd5c3259f4822735a2; } // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) { res += 0x01000000000000000000000000000000; x = (x * FIXED_1) / 0x810100ab00222d861931c15e39b44e99; } // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) { res += 0x00800000000000000000000000000000; x = (x * FIXED_1) / 0x808040155aabbbe9451521693554f733; } // add 1 / 2^8 z = y = x - FIXED_1; w = (y * y) / FIXED_1; res += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 res += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 res += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 res += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 res += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 res += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 res += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 res += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - 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 optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } }
Approve token allowance Emits an Approval event upon success/
function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); }
1,269,424
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/Verifiers.sol
Computes the bulk order hash for the specified proof and leaf. proofAndSignature The proof and signature of the bulk order. leaf The leaf of the bulk order tree. return bulkOrderHash The bulk order hash./ Declare arguments for the root hash and the height of the proof. Utilize assembly to efficiently derive the root hash using the proof. Retrieve the length of the proof, key, and signature combined. If proofAndSignature has odd length, it is a compact signature with 64 bytes. Derive height (or depth of tree) with signature and proof length. Update the length in memory to only include the signature. Derive the pointer for the key using the signature length. Retrieve the three-byte key using the derived pointer. for the key size to the derived key pointer. Compute level 1. Compute remaining proofs. Use the typehash and the root hash to derive final bulk order hash.
function _computeBulkOrderProof( bytes memory proofAndSignature, bytes32 leaf ) internal view returns (bytes32 bulkOrderHash) { bytes32 root; uint256 height; assembly { let fullLength := mload(proofAndSignature) let signatureLength := sub(ECDSA_MaxLength, and(fullLength, 1)) height := shr(OneWordShift, sub(fullLength, signatureLength)) mstore(proofAndSignature, signatureLength) let keyPtr := add(proofAndSignature, add(OneWord, signatureLength)) let key := shr(BulkOrderProof_keyShift, mload(keyPtr)) let proof := add(keyPtr, BulkOrderProof_keySize) let scratchPtr1 := shl(OneWordShift, and(key, 1)) mstore(scratchPtr1, leaf) mstore(xor(scratchPtr1, OneWord), mload(proof)) for { let i := 1 i := add(i, 1) proof := add(proof, OneWord) let scratchPtr := shl(OneWordShift, and(shr(i, key), 1)) mstore(scratchPtr, keccak256(0, TwoWords)) mstore(xor(scratchPtr, OneWord), mload(proof)) } } assembly { mstore(0, rootTypeHash) mstore(OneWord, root) bulkOrderHash := keccak256(0, TwoWords) } }
4,301,134
./full_match/137/0xe558726C468Ccc21cc09ca4B8B46131dC1002923/sources/project_/contracts/Exchange.sol
Settles a liquidity addition by transferring deposited assets from wallet balances to pool reserves and minting LP tokens addition A `LiquidityAddition` struct encoding the parameters of the addition requested by the user either on-chain via `addLiquidity` or `addLiquidityETH` or off-chain via ECDSA-signed API request execution A `LiquidityChangeExecution` struct encoding the parameters of this liquidity addition execution that meets the terms of the request/
function executeAddLiquidity( LiquidityAddition calldata addition, LiquidityChangeExecution calldata execution ) external onlyDispatcher { require(!isWalletExitFinalized(addition.wallet), 'Wallet exit finalized'); _liquidityPools.executeAddLiquidity( addition, execution, _feeWallet, address(_custodian), _balanceTracking ); emit LiquidityAdditionExecuted( addition.wallet, execution.baseAssetAddress, execution.quoteAssetAddress, execution.grossBaseQuantityInPips, execution.grossQuoteQuantityInPips, execution.liquidityInPips ); }
4,761,986
./full_match/43114/0xDFb772ABfBC6B8D7028c44b9047c334C612cd1f2/sources/contracts/MultiChainFuture.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, 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); }
4,615,985
./partial_match/1/0xda99cbAaa7307D4e0c3D1CF83D459f9ad729e9C8/sources/contracts/twap/libraries/TwapShareHelper.sol
Calculates the fee shares from accumulated fees _factory Strategy factory address _manager Strategy manager contract address _fee0 Accumulated token0 fee amount _fee1 Accumulated token1 fee amount/ protocol fees performance fee to manager protocol performance fee calculate the fees for protocol and manager from performance fees
function calculateFeeTokenShares( ITwapStrategyFactory _factory, ITwapStrategyManager _manager, uint256 _fee0, uint256 _fee1 ) public view returns ( address managerFeeTo, address protocolFeeTo, uint256 managerToken0Amount, uint256 managerToken1Amount, uint256 protocolToken0Amount, uint256 protocolToken1Amount ) { uint256 protocolFeeRate = _factory.protocolFeeRate(); uint256 performanceFeeRate = _manager.performanceFeeRate(); uint256 protocolPerformanceFeeRate = _factory.protocolPerformanceFeeRate(); uint256 performanceToken0Amount = FullMath.mulDiv(_fee0, performanceFeeRate, 1e8); uint256 performanceToken1Amount = FullMath.mulDiv(_fee1, performanceFeeRate, 1e8); if (performanceToken0Amount > 0) { protocolToken0Amount = FullMath.mulDiv(performanceToken0Amount, protocolFeeRate, 1e8); managerToken0Amount = performanceToken0Amount.sub(protocolToken0Amount); } if (performanceToken1Amount > 0) { protocolToken1Amount = FullMath.mulDiv(performanceToken1Amount, protocolFeeRate, 1e8); managerToken1Amount = performanceToken1Amount.sub(protocolToken1Amount); } protocolToken0Amount = protocolToken0Amount.add(FullMath.mulDiv(_fee0, protocolPerformanceFeeRate, 1e8)); protocolToken1Amount = protocolToken1Amount.add(FullMath.mulDiv(_fee1, protocolPerformanceFeeRate, 1e8)); protocolFeeTo = _factory.feeTo(); }
3,692,630
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; // (Uni|Pancake)Swap libs are interchangeable import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol"; import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; /* For lines that are marked ERC20 Token Standard, learn more at https://eips.ethereum.org/EIPS/eip-20. */ contract ERC20Deflationary is Context, IERC20, Ownable { // Keeps track of balances for address that are included in receiving reward. mapping (address => uint256) private _reflectionBalances; // Keeps track of balances for address that are excluded from receiving reward. mapping (address => uint256) private _tokenBalances; // Keeps track of which address are excluded from fee. mapping (address => bool) private _isExcludedFromFee; // Keeps track of which address are excluded from reward. mapping (address => bool) private _isExcludedFromReward; // An array of addresses that are excluded from reward. address[] private _excludedFromReward; // ERC20 Token Standard mapping (address => mapping (address => uint256)) private _allowances; // Liquidity pool provider router IUniswapV2Router02 internal _uniswapV2Router; // This Token and WETH pair contract address. address internal _uniswapV2Pair; // Where burnt tokens are sent to. This is an address that no one can have accesses to. address private constant burnAccount = 0x000000000000000000000000000000000000dEaD; /* Tax rate = (_taxXXX / 10**_tax_XXXDecimals) percent. For example: if _taxBurn is 1 and _taxBurnDecimals is 2. Tax rate = 0.01% If you want tax rate for burn to be 5% for example, set _taxBurn to 5 and _taxBurnDecimals to 0. 5 * (10 ** 0) = 5 */ // Decimals of taxBurn. Used for have tax less than 1%. uint8 private _taxBurnDecimals; // Decimals of taxReward. Used for have tax less than 1%. uint8 private _taxRewardDecimals; // Decimals of taxLiquify. Used for have tax less than 1%. uint8 private _taxLiquifyDecimals; // This percent of a transaction will be burnt. uint8 private _taxBurn; // This percent of a transaction will be redistribute to all holders. uint8 private _taxReward; // This percent of a transaction will be added to the liquidity pool. More details at https://github.com/Sheldenshi/ERC20Deflationary. uint8 private _taxLiquify; // ERC20 Token Standard uint8 private _decimals; // ERC20 Token Standard uint256 private _totalSupply; // Current supply:= total supply - burnt tokens uint256 private _currentSupply; // A number that helps distributing fees to all holders respectively. uint256 private _reflectionTotal; // Total amount of tokens rewarded / distributing. uint256 private _totalRewarded; // Total amount of tokens burnt. uint256 private _totalBurnt; // Total amount of tokens locked in the LP (this token and WETH pair). uint256 private _totalTokensLockedInLiquidity; // Total amount of ETH locked in the LP (this token and WETH pair). uint256 private _totalETHLockedInLiquidity; // A threshold for swap and liquify. uint256 private _minTokensBeforeSwap; // ERC20 Token Standard string private _name; // ERC20 Token Standard string private _symbol; // Whether a previous call of SwapAndLiquify process is still in process. bool private _inSwapAndLiquify; bool private _autoSwapAndLiquifyEnabled; bool private _autoBurnEnabled; bool private _rewardEnabled; // Prevent reentrancy. modifier lockTheSwap { require(!_inSwapAndLiquify, "Currently in swap and liquify."); _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } // Return values of _getValues function. struct ValuesFromAmount { // Amount of tokens for to transfer. uint256 amount; // Amount tokens charged for burning. uint256 tBurnFee; // Amount tokens charged to reward. uint256 tRewardFee; // Amount tokens charged to add to liquidity. uint256 tLiquifyFee; // Amount tokens after fees. uint256 tTransferAmount; // Reflection of amount. uint256 rAmount; // Reflection of burn fee. uint256 rBurnFee; // Reflection of reward fee. uint256 rRewardFee; // Reflection of liquify fee. uint256 rLiquifyFee; // Reflection of transfer amount. uint256 rTransferAmount; } /* Events */ event Burn(address from, uint256 amount); event TaxBurnUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxRewardUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxLiquifyUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event MinTokensBeforeSwapUpdated(uint256 previous, uint256 current); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensAddedToLiquidity ); event ExcludeAccountFromReward(address account); event IncludeAccountInReward(address account); event ExcludeAccountFromFee(address account); event IncludeAccountInFee(address account); event EnabledAutoBurn(); event EnabledReward(); event EnabledAutoSwapAndLiquify(); event DisabledAutoBurn(); event DisabledReward(); event DisabledAutoSwapAndLiquify(); event Airdrop(uint256 amount); constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 tokenSupply_) { // Sets the values for `name`, `symbol`, `totalSupply`, `currentSupply`, and `rTotal`. _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = tokenSupply_ * (10 ** decimals_); _currentSupply = _totalSupply; _reflectionTotal = (~uint256(0) - (~uint256(0) % _totalSupply)); // Mint _reflectionBalances[_msgSender()] = _reflectionTotal; // exclude owner and this contract from fee. excludeAccountFromFee(owner()); excludeAccountFromFee(address(this)); // exclude owner, burnAccount, and this contract from receiving rewards. _excludeAccountFromReward(owner()); _excludeAccountFromReward(burnAccount); _excludeAccountFromReward(address(this)); emit Transfer(address(0), _msgSender(), _totalSupply); } // allow the contract to receive ETH receive() external payable {} /** * @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`). * * 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 _decimals; } /** * @dev Returns the address of this token and WETH pair. */ function uniswapV2Pair() public view virtual returns (address) { return _uniswapV2Pair; } /** * @dev Returns the current burn tax. */ function taxBurn() public view virtual returns (uint8) { return _taxBurn; } /** * @dev Returns the current reward tax. */ function taxReward() public view virtual returns (uint8) { return _taxReward; } /** * @dev Returns the current liquify tax. */ function taxLiquify() public view virtual returns (uint8) { return _taxLiquify; } /** * @dev Returns the current burn tax decimals. */ function taxBurnDecimals() public view virtual returns (uint8) { return _taxBurnDecimals; } /** * @dev Returns the current reward tax decimals. */ function taxRewardDecimals() public view virtual returns (uint8) { return _taxRewardDecimals; } /** * @dev Returns the current liquify tax decimals. */ function taxLiquifyDecimals() public view virtual returns (uint8) { return _taxLiquifyDecimals; } /** * @dev Returns true if auto burn feature is enabled. */ function autoBurnEnabled() public view virtual returns (bool) { return _autoBurnEnabled; } /** * @dev Returns true if reward feature is enabled. */ function rewardEnabled() public view virtual returns (bool) { return _rewardEnabled; } /** * @dev Returns true if auto swap and liquify feature is enabled. */ function autoSwapAndLiquifyEnabled() public view virtual returns (bool) { return _autoSwapAndLiquifyEnabled; } /** * @dev Returns the threshold before swap and liquify. */ function minTokensBeforeSwap() external view virtual returns (uint256) { return _minTokensBeforeSwap; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns current supply of the token. * (currentSupply := totalSupply - totalBurnt) */ function currentSupply() external view virtual returns (uint256) { return _currentSupply; } /** * @dev Returns the total number of tokens burnt. */ function totalBurnt() external view virtual returns (uint256) { return _totalBurnt; } /** * @dev Returns the total number of tokens locked in the LP. */ function totalTokensLockedInLiquidity() external view virtual returns (uint256) { return _totalTokensLockedInLiquidity; } /** * @dev Returns the total number of ETH locked in the LP. */ function totalETHLockedInLiquidity() external view virtual returns (uint256) { return _totalETHLockedInLiquidity; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { if (_isExcludedFromReward[account]) return _tokenBalances[account]; return tokenFromReflection(_reflectionBalances[account]); } /** * @dev Returns whether an account is excluded from reward. */ function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedFromReward[account]; } /** * @dev Returns whether an account is excluded from fee. */ function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[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); require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - 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 Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Burn} event indicating the amount burnt. * Emits a {Transfer} event with `to` set to the burn 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 != burnAccount, "ERC20: burn from the burn address"); uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); uint256 rAmount = _getRAmount(amount); // Transfer from account to the burnAccount if (_isExcludedFromReward[account]) { _tokenBalances[account] -= amount; } _reflectionBalances[account] -= rAmount; _tokenBalances[burnAccount] += amount; _reflectionBalances[burnAccount] += rAmount; _currentSupply -= amount; _totalBurnt += amount; emit Burn(account, amount); emit Transfer(account, burnAccount, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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"); ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]); if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferFromExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferToExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferStandard(sender, recipient, values); } else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferBothExcluded(sender, recipient, values); } else { _transferStandard(sender, recipient, values); } emit Transfer(sender, recipient, values.tTransferAmount); if (!_isExcludedFromFee[sender]) { _afterTokenTransfer(values); } } /** * @dev Performs all the functionalities that are enabled. */ function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual { // Burn if (_autoBurnEnabled) { _tokenBalances[address(this)] += values.tBurnFee; _reflectionBalances[address(this)] += values.rBurnFee; _approve(address(this), _msgSender(), values.tBurnFee); burnFrom(address(this), values.tBurnFee); } // Reflect if (_rewardEnabled) { _distributeFee(values.rRewardFee, values.tRewardFee); } // Add to liquidity pool if (_autoSwapAndLiquifyEnabled) { // add liquidity fee to this contract. _tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; uint256 contractBalance = _tokenBalances[address(this)]; // whether the current contract balances makes the threshold to swap and liquify. bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap; if (overMinTokensBeforeSwap && !_inSwapAndLiquify && _msgSender() != _uniswapV2Pair && _autoSwapAndLiquifyEnabled ) { swapAndLiquify(contractBalance); } } } /** * @dev Performs transfer between two accounts that are both included in receiving reward. */ function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an included account to an excluded account. * (included and excluded from receiving reward.) */ function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an excluded account to an included account. * (included and excluded from receiving reward.) */ function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer between two accounts that are both excluded in receiving reward. */ function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Destroys `amount` tokens from the caller. * */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } /** * @dev Excludes an account from receiving reward. * * Emits a {ExcludeAccountFromReward} event. * * Requirements: * * - `account` is included in receiving reward. */ function _excludeAccountFromReward(address account) internal { require(!_isExcludedFromReward[account], "Account is already excluded."); if(_reflectionBalances[account] > 0) { _tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); emit ExcludeAccountFromReward(account); } /** * @dev Includes an account from receiving reward. * * Emits a {IncludeAccountInReward} event. * * Requirements: * * - `account` is excluded in receiving reward. */ function _includeAccountInReward(address account) internal { require(_isExcludedFromReward[account], "Account is already included."); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tokenBalances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } emit IncludeAccountInReward(account); } /** * @dev Excludes an account from fee. * * Emits a {ExcludeAccountFromFee} event. * * Requirements: * * - `account` is included in fee. */ function excludeAccountFromFee(address account) internal { require(!_isExcludedFromFee[account], "Account is already excluded."); _isExcludedFromFee[account] = true; emit ExcludeAccountFromFee(account); } /** * @dev Includes an account from fee. * * Emits a {IncludeAccountFromFee} event. * * Requirements: * * - `account` is excluded in fee. */ function includeAccountInFee(address account) internal { require(_isExcludedFromFee[account], "Account is already included."); _isExcludedFromFee[account] = false; emit IncludeAccountInFee(account); } /** * @dev Airdrop tokens to all holders that are included from reward. * Requirements: * - the caller must have a balance of at least `amount`. */ function airdrop(uint256 amount) public { address sender = _msgSender(); //require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); require(balanceOf(sender) >= amount, "The caller must have balance >= amount."); ValuesFromAmount memory values = _getValues(amount, false); if (_isExcludedFromReward[sender]) { _tokenBalances[sender] -= values.amount; } _reflectionBalances[sender] -= values.rAmount; _reflectionTotal = _reflectionTotal - values.rAmount; _totalRewarded += amount ; emit Airdrop(amount); } /** * @dev Returns the reflected amount of a token. * Requirements: * - `amount` must be less than total supply. */ function reflectionFromToken(uint256 amount, bool deductTransferFee) internal view returns(uint256) { require(amount <= _totalSupply, "Amount must be less than supply"); ValuesFromAmount memory values = _getValues(amount, deductTransferFee); return values.rTransferAmount; } /** * @dev Used to figure out the balance after reflection. * Requirements: * - `rAmount` must be less than reflectTotal. */ function tokenFromReflection(uint256 rAmount) internal view returns(uint256) { require(rAmount <= _reflectionTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } /** * @dev Swap half of contract's token balance for ETH, * and pair it up with the other half to add to the * liquidity pool. * * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth, * the amount of ETH added to the LP, and the amount of tokens added to the LP. */ function swapAndLiquify(uint256 contractBalance) private lockTheSwap { // Split the contract balance into two halves. uint256 tokensToSwap = contractBalance / 2; uint256 tokensAddToLiquidity = contractBalance - tokensToSwap; // Contract's current ETH balance. uint256 initialBalance = address(this).balance; // Swap half of the tokens to ETH. swapTokensForEth(tokensToSwap); // Figure out the exact amount of tokens received from swapping. uint256 ethAddToLiquify = address(this).balance - initialBalance; // Add to the LP of this token and WETH pair (half ETH and half this token). addLiquidity(ethAddToLiquify, tokensAddToLiquidity); _totalETHLockedInLiquidity += address(this).balance - initialBalance; _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this)); emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity); } /** * @dev Swap `amount` tokens for ETH. * * Emits {Transfer} event. From this contract to the token and WETH Pair. */ function swapTokensForEth(uint256 amount) private { // Generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), // this contract will receive the eth that were swapped from the token block.timestamp + 60 * 1000 ); } /** * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP. * Depends on the current rate for the pair between this token and WETH, * `ethAmount` and `tokenAmount` might not match perfectly. * Dust(leftover) ETH or token will be refunded to this contract * (usually very small quantity). * * Emits {Transfer} event. From this contract to the token and WETH Pai. */ function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); } /** * @dev Distribute the `tRewardFee` tokens to all holders that are included in receiving reward. * amount received is based on how many token one owns. */ function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private { // This would decrease rate, thus increase amount reward receive based on one's balance. _reflectionTotal = _reflectionTotal - rRewardFee; _totalRewarded += tRewardFee; } /** * @dev Returns fees and transfer amount in both tokens and reflections. * tXXXX stands for tokenXXXX * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) { ValuesFromAmount memory values; values.amount = amount; _getTValues(values, deductTransferFee); _getRValues(values, deductTransferFee); return values; } /** * @dev Adds fees and transfer amount in tokens to `values`. * tXXXX stands for tokenXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private { if (deductTransferFee) { values.tTransferAmount = values.amount; } else { // calculate fee values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals); values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals); values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals); // amount after fee values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee; } } /** * @dev Adds fees and transfer amount in reflection to `values`. * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private { uint256 currentRate = _getRate(); values.rAmount = values.amount * currentRate; if (deductTransferFee) { values.rTransferAmount = values.rAmount; } else { values.rAmount = values.amount * currentRate; values.rBurnFee = values.tBurnFee * currentRate; values.rRewardFee = values.tRewardFee * currentRate; values.rLiquifyFee = values.tLiquifyFee * currentRate; values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee; } } /** * @dev Returns `amount` in reflection. */ function _getRAmount(uint256 amount) private view returns (uint256) { uint256 currentRate = _getRate(); return amount * currentRate; } /** * @dev Returns the current reflection rate. */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } /** * @dev Returns the current reflection supply and token supply. */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _reflectionTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply); rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]]; tSupply = tSupply - _tokenBalances[_excludedFromReward[i]]; } if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply); return (rSupply, tSupply); } /** * @dev Returns fee based on `amount` and `taxRate` */ function _calculateTax(uint256 amount, uint8 tax, uint8 taxDecimals_) private pure returns (uint256) { return amount * tax / (10 ** taxDecimals_) / (10 ** 2); } /* Owner functions */ /** * @dev Enables the auto burn feature. * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled. * * Emits a {EnabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(!_autoBurnEnabled, "Auto burn feature is already enabled."); require(taxBurn_ > 0, "Tax must be greater than 0."); require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _autoBurnEnabled = true; setTaxBurn(taxBurn_, taxBurnDecimals_); emit EnabledAutoBurn(); } /** * @dev Enables the reward feature. * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled. * * Emits a {EnabledReward} event. * * Requirements: * * - reward feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(!_rewardEnabled, "Reward feature is already enabled."); require(taxReward_ > 0, "Tax must be greater than 0."); require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _rewardEnabled = true; setTaxReward(taxReward_, taxRewardDecimals_); emit EnabledReward(); } /** * @dev Enables the auto swap and liquify feature. * Swaps half of transaction amount * `taxLiquify_` amount of tokens * to ETH and pair with the other half of tokens to the LP each transaction when enabled. * * Emits a {EnabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner { require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled."); require(taxLiquify_ > 0, "Tax must be greater than 0."); require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _minTokensBeforeSwap = minTokensBeforeSwap_; // init Router IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress); _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH()); if (_uniswapV2Pair == address(0)) { _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); } _uniswapV2Router = uniswapV2Router; // exclude uniswapV2Router from receiving reward. _excludeAccountFromReward(address(uniswapV2Router)); // exclude WETH and this Token Pair from receiving reward. _excludeAccountFromReward(_uniswapV2Pair); // exclude uniswapV2Router from paying fees. excludeAccountFromFee(address(uniswapV2Router)); // exclude WETH and this Token Pair from paying fees. excludeAccountFromFee(_uniswapV2Pair); // enable _autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify(); } /** * @dev Disables the auto burn feature. * * Emits a {DisabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be enabled. */ function disableAutoBurn() public onlyOwner { require(_autoBurnEnabled, "Auto burn feature is already disabled."); setTaxBurn(0, 0); _autoBurnEnabled = false; emit DisabledAutoBurn(); } /** * @dev Disables the reward feature. * * Emits a {DisabledReward} event. * * Requirements: * * - reward feature mush be enabled. */ function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); } /** * @dev Disables the auto swap and liquify feature. * * Emits a {DisabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be enabled. */ function disableAutoSwapAndLiquify() public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already disabled."); setTaxLiquify(0, 0); _autoSwapAndLiquifyEnabled = false; emit DisabledAutoSwapAndLiquify(); } /** * @dev Updates `_minTokensBeforeSwap` * * Emits a {MinTokensBeforeSwap} event. * * Requirements: * * - `minTokensBeforeSwap_` must be less than _currentSupply. */ function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner { require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply."); uint256 previous = _minTokensBeforeSwap; _minTokensBeforeSwap = minTokensBeforeSwap_; emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap); } /** * @dev Updates taxBurn * * Emits a {TaxBurnUpdate} event. * * Requirements: * * - auto burn feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function."); require(taxBurn_ + _taxReward + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxBurn; uint8 previousDecimals = _taxBurnDecimals; _taxBurn = taxBurn_; _taxBurnDecimals = taxBurnDecimals_; emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_); } /** * @dev Updates taxReward * * Emits a {TaxRewardUpdate} event. * * Requirements: * * - reward feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function."); require(_taxBurn + taxReward_ + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxReward; uint8 previousDecimals = _taxRewardDecimals; _taxReward = taxReward_; _taxBurnDecimals = taxRewardDecimals_; emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_); } /** * @dev Updates taxLiquify * * Emits a {TaxLiquifyUpdate} event. * * Requirements: * * - auto swap and liquify feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function."); require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high."); uint8 previousTax = _taxLiquify; uint8 previousDecimals = _taxLiquifyDecimals; _taxLiquify = taxLiquify_; _taxLiquifyDecimals = taxLiquifyDecimals_; emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_); } }
Updates taxLiquify Emits a {TaxLiquifyUpdate} event. Requirements: - auto swap and liquify feature must be enabled. - total tax rate must be less than 100%./
function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function."); require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high."); uint8 previousTax = _taxLiquify; uint8 previousDecimals = _taxLiquifyDecimals; _taxLiquify = taxLiquify_; _taxLiquifyDecimals = taxLiquifyDecimals_; emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_); }
916,846
pragma solidity 0.5.11; library SafeMath { function ADD640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB596(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB596(a, b, "SafeMath: subtraction overflow"); } function SUB596(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 MUL119(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 DIV27(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV27(a, b, "SafeMath: division by zero"); } function DIV27(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 MOD463(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD463(a, b, "SafeMath: modulo by zero"); } function MOD463(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract InscribableToken { mapping(bytes32 => bytes32) public properties; event CLASSPROPERTYSET751( //inject NONSTANDARD NAMING bytes32 indexed key, bytes32 value ); event TOKENPROPERTYSET338( //inject NONSTANDARD NAMING uint indexed id, bytes32 indexed key, bytes32 value ); function _SETPROPERTY292( //inject NONSTANDARD NAMING uint _id, bytes32 _key, bytes32 _value ) internal { properties[GETTOKENKEY33(_id, _key)] = _value; emit TOKENPROPERTYSET338(_id, _key, _value); } function GETPROPERTY470( //inject NONSTANDARD NAMING uint _id, bytes32 _key ) public view returns (bytes32 _value) { return properties[GETTOKENKEY33(_id, _key)]; } function _SETCLASSPROPERTY718( //inject NONSTANDARD NAMING bytes32 _key, bytes32 _value ) internal { emit CLASSPROPERTYSET751(_key, _value); properties[GETCLASSKEY628(_key)] = _value; } function GETTOKENKEY33( //inject NONSTANDARD NAMING uint _tokenId, bytes32 _key ) public pure returns (bytes32) { // one prefix to prevent collisions return keccak256(abi.encodePacked(uint(1), _tokenId, _key)); } function GETCLASSKEY628(bytes32 _key) //inject NONSTANDARD NAMING public pure returns (bytes32) { // zero prefix to prevent collisions return keccak256(abi.encodePacked(uint(0), _key)); } function GETCLASSPROPERTY691(bytes32 _key) //inject NONSTANDARD NAMING public view returns (bytes32) { return properties[GETCLASSKEY628(_key)]; } } library String { function FROMUINT947(uint256 value) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } bytes constant alphabet572 = "0123456789abcdef"; //inject NONSTANDARD NAMING function FROMADDRESS777(address _addr) internal pure returns(string memory) { //inject NONSTANDARD NAMING bytes32 value = bytes32(uint256(_addr)); bytes memory str = new bytes(42); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet572[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet572[uint(uint8(value[i + 12] & 0x0F))]; } return string(str); } } // solium-disable security/no-inline-assembly library StorageWrite { using SafeMath for uint256; function _GETSTORAGEARRAYSLOT595(uint _dest, uint _index) internal view returns (uint result) { //inject NONSTANDARD NAMING uint slot = _GETARRAYSLOT364(_dest, _index); assembly { result := sload(slot) } } function _GETARRAYSLOT364(uint _dest, uint _index) internal pure returns (uint slot) { //inject NONSTANDARD NAMING assembly { let free := mload(0x40) mstore(free, _dest) slot := add(keccak256(free, 32), _index) } } function _SETARRAYSLOT66(uint _dest, uint _index, uint _value) internal { //inject NONSTANDARD NAMING uint slot = _GETARRAYSLOT364(_dest, _index); assembly { sstore(slot, _value) } } function _LOADSLOTS761( //inject NONSTANDARD NAMING uint _slot, uint _offset, uint _perSlot, uint _length ) internal view returns (uint[] memory slots) { uint slotCount = _SLOTCOUNT226(_offset, _perSlot, _length); slots = new uint[](slotCount); // top and tail the slots uint firstPos = _POS762(_offset, _perSlot); // _offset.div(_perSlot); slots[0] = _GETSTORAGEARRAYSLOT595(_slot, firstPos); if (slotCount > 1) { uint lastPos = _POS762(_offset.ADD640(_length), _perSlot); // .div(_perSlot); slots[slotCount-1] = _GETSTORAGEARRAYSLOT595(_slot, lastPos); } } function _POS762(uint items, uint perPage) internal pure returns (uint) { //inject NONSTANDARD NAMING return items / perPage; } function _SLOTCOUNT226(uint _offset, uint _perSlot, uint _length) internal pure returns (uint) { //inject NONSTANDARD NAMING uint start = _offset / _perSlot; uint end = (_offset + _length) / _perSlot; return (end - start) + 1; } function _SAVESLOTS992(uint _slot, uint _offset, uint _size, uint[] memory _slots) internal { //inject NONSTANDARD NAMING uint offset = _offset.DIV27((256/_size)); for (uint i = 0; i < _slots.length; i++) { _SETARRAYSLOT66(_slot, offset + i, _slots[i]); } } function _WRITE724(uint[] memory _slots, uint _offset, uint _size, uint _index, uint _value) internal pure { //inject NONSTANDARD NAMING uint perSlot = 256 / _size; uint initialOffset = _offset % perSlot; uint slotPosition = (initialOffset + _index) / perSlot; uint withinSlot = ((_index + _offset) % perSlot) * _size; // evil bit shifting magic for (uint q = 0; q < _size; q += 8) { _slots[slotPosition] |= ((_value >> q) & 0xFF) << (withinSlot + q); } } function REPEATUINT16794(uint _slot, uint _offset, uint _length, uint16 _item) internal { //inject NONSTANDARD NAMING uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _length); for (uint i = 0; i < _length; i++) { _WRITE724(slots, _offset, 16, i, _item); } _SAVESLOTS992(_slot, _offset, 16, slots); } function UINT16S436(uint _slot, uint _offset, uint16[] memory _items) internal { //inject NONSTANDARD NAMING uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _items.length); for (uint i = 0; i < _items.length; i++) { _WRITE724(slots, _offset, 16, i, _items[i]); } _SAVESLOTS992(_slot, _offset, 16, slots); } function UINT8S318(uint _slot, uint _offset, uint8[] memory _items) internal { //inject NONSTANDARD NAMING uint[] memory slots = _LOADSLOTS761(_slot, _offset, 32, _items.length); for (uint i = 0; i < _items.length; i++) { _WRITE724(slots, _offset, 8, i, _items[i]); } _SAVESLOTS992(_slot, _offset, 8, slots); } } contract ImmutableToken { string public constant baseuri257 = "https://api.immutable.com/asset/"; //inject NONSTANDARD NAMING function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING return string(abi.encodePacked( baseuri257, String.FROMADDRESS777(address(this)), "/", String.FROMUINT947(tokenId) )); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER48() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA774() internal view 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; } } interface IERC165 { function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING } contract ERC165 is IERC165 { bytes4 private constant _interface_id_erc165383 = 0x01ffc9a7; //inject NONSTANDARD NAMING mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _REGISTERINTERFACE770(_interface_id_erc165383); } function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING return _supportedInterfaces[interfaceId]; } function _REGISTERINTERFACE770(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } contract IERC721Receiver { function ONERC721RECEIVED640(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING public returns (bytes4); } library Address { function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE665(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE550(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library Counters { using SafeMath for uint256; 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 CURRENT711(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING return counter._value; } function INCREMENT113(Counter storage counter) internal { //inject NONSTANDARD NAMING counter._value += 1; } function DECREMENT390(Counter storage counter) internal { //inject NONSTANDARD NAMING counter._value = counter._value.SUB596(1); } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED114(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER48(); emit OWNERSHIPTRANSFERRED114(address(0), _owner); } function OWNER177() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER453() { //inject NONSTANDARD NAMING require(ISOWNER434(), "Ownable: caller is not the owner"); _; } function ISOWNER434() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER48() == _owner; } function RENOUNCEOWNERSHIP876() public ONLYOWNER453 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED114(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP194(address newOwner) public ONLYOWNER453 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP3(newOwner); } function _TRANSFEROWNERSHIP3(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED114(_owner, newOwner); _owner = newOwner; } } contract IERC721 is IERC165 { event TRANSFER336(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL97(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL640(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF188(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF127(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function TRANSFERFROM301(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function APPROVE921(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED252(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL542(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _erc721_received341 = 0x150b7a02; //inject NONSTANDARD NAMING // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _interface_id_erc721248 = 0x80ac58cd; //inject NONSTANDARD NAMING constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE770(_interface_id_erc721248); } function BALANCEOF188(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].CURRENT711(); } function OWNEROF127(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF127(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_MSGSENDER48() == owner || ISAPPROVEDFORALL999(owner, _MSGSENDER48()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit APPROVAL97(owner, to, tokenId); } function GETAPPROVED252(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function SETAPPROVALFORALL542(address to, bool approved) public { //inject NONSTANDARD NAMING require(to != _MSGSENDER48(), "ERC721: approve to caller"); _operatorApprovals[_MSGSENDER48()][to] = approved; emit APPROVALFORALL640(_MSGSENDER48(), to, approved); } function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING return _operatorApprovals[owner][operator]; } function TRANSFERFROM301(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING //solhint-disable-next-line max-line-length require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved"); _TRANSFERFROM539(from, to, tokenId); } function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING SAFETRANSFERFROM19(from, to, tokenId, ""); } function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved"); _SAFETRANSFERFROM254(from, to, tokenId, _data); } function _SAFETRANSFERFROM254(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _TRANSFERFROM539(from, to, tokenId); require(_CHECKONERC721RECEIVED206(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _EXISTS289(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; return owner != address(0); } function _ISAPPROVEDOROWNER149(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721: operator query for nonexistent token"); address owner = OWNEROF127(tokenId); return (spender == owner || GETAPPROVED252(tokenId) == spender || ISAPPROVEDFORALL999(owner, spender)); } function _SAFEMINT5(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING _SAFEMINT5(to, tokenId, ""); } function _SAFEMINT5(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _MINT330(to, tokenId); require(_CHECKONERC721RECEIVED206(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _MINT330(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(to != address(0), "ERC721: mint to the zero address"); require(!_EXISTS289(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].INCREMENT113(); emit TRANSFER336(address(0), to, tokenId); } function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF127(tokenId) == owner, "ERC721: burn of token that is not own"); _CLEARAPPROVAL340(tokenId); _ownedTokensCount[owner].DECREMENT390(); _tokenOwner[tokenId] = address(0); emit TRANSFER336(owner, address(0), tokenId); } function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING _BURN121(OWNEROF127(tokenId), tokenId); } function _TRANSFERFROM539(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF127(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _CLEARAPPROVAL340(tokenId); _ownedTokensCount[from].DECREMENT390(); _ownedTokensCount[to].INCREMENT113(); _tokenOwner[tokenId] = to; emit TRANSFER336(from, to, tokenId); } function _CHECKONERC721RECEIVED206(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING internal returns (bool) { if (!to.ISCONTRACT794()) { return true; } bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED640(_MSGSENDER48(), from, tokenId, _data); return (retval == _erc721_received341); } function _CLEARAPPROVAL340(uint256 tokenId) private { //inject NONSTANDARD NAMING if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract IERC721Metadata is IERC721 { function NAME105() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL26() external view returns (string memory); //inject NONSTANDARD NAMING function TOKENURI642(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING } contract MultiTransfer is IERC721 { function TRANSFERBATCH764( //inject NONSTANDARD NAMING address from, address to, uint256 start, uint256 end ) public { for (uint i = start; i < end; i++) { TRANSFERFROM301(from, to, i); } } function TRANSFERALLFROM512( //inject NONSTANDARD NAMING address from, address to, uint256[] memory tokenIDs ) public { for (uint i = 0; i < tokenIDs.length; i++) { TRANSFERFROM301(from, to, tokenIDs[i]); } } function SAFETRANSFERBATCH319( //inject NONSTANDARD NAMING address from, address to, uint256 start, uint256 end ) public { for (uint i = start; i < end; i++) { SAFETRANSFERFROM19(from, to, i); } } function SAFETRANSFERALLFROM526( //inject NONSTANDARD NAMING address from, address to, uint256[] memory tokenIDs ) public { for (uint i = 0; i < tokenIDs.length; i++) { SAFETRANSFERFROM19(from, to, tokenIDs[i]); } } } contract ICards is IERC721 { struct Batch { uint48 userID; uint16 size; } function BATCHES528(uint index) public view returns (uint48 userID, uint16 size); //inject NONSTANDARD NAMING function USERIDTOADDRESS44(uint48 id) public view returns (address); //inject NONSTANDARD NAMING function GETDETAILS612( //inject NONSTANDARD NAMING uint tokenId ) public view returns ( uint16 proto, uint8 quality ); function SETQUALITY366( //inject NONSTANDARD NAMING uint tokenId, uint8 quality ) public; function MINTCARDS596( //inject NONSTANDARD NAMING address to, uint16[] memory _protos, uint8[] memory _qualities ) public returns (uint); function MINTCARD737( //inject NONSTANDARD NAMING address to, uint16 _proto, uint8 _quality ) public returns (uint); function BURN6(uint tokenId) public; //inject NONSTANDARD NAMING function BATCHSIZE292() //inject NONSTANDARD NAMING public view returns (uint); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant _interface_id_erc721_metadata499 = 0x5b5e139f; //inject NONSTANDARD NAMING constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE770(_interface_id_erc721_metadata499); } function NAME105() external view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL26() external view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } function _SETTOKENURI974(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN121(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract BatchToken is ERC721Metadata { using SafeMath for uint256; struct Batch { uint48 userID; uint16 size; } mapping(uint48 => address) public userIDToAddress; mapping(address => uint48) public addressToUserID; uint256 public batchSize; uint256 public nextBatch; uint256 public tokenCount; uint48[] internal ownerIDs; uint48[] internal approvedIDs; mapping(uint => Batch) public batches; uint48 internal userCount = 1; mapping(address => uint) internal _balances; uint256 internal constant max_length549 = uint(2**256 - 1); //inject NONSTANDARD NAMING constructor( uint256 _batchSize, string memory name, string memory symbol ) public ERC721Metadata(name, symbol) { batchSize = _batchSize; ownerIDs.length = max_length549; approvedIDs.length = max_length549; } function _GETUSERID7(address to) //inject NONSTANDARD NAMING internal returns (uint48) { if (to == address(0)) { return 0; } uint48 uID = addressToUserID[to]; if (uID == 0) { require( userCount + 1 > userCount, "BT: must not overflow" ); uID = userCount++; userIDToAddress[uID] = to; addressToUserID[to] = uID; } return uID; } function _BATCHMINT199( //inject NONSTANDARD NAMING address to, uint16 size ) internal returns (uint) { require( to != address(0), "BT: must not be null" ); require( size > 0 && size <= batchSize, "BT: size must be within limits" ); uint256 start = nextBatch; uint48 uID = _GETUSERID7(to); batches[start] = Batch({ userID: uID, size: size }); uint256 end = start.ADD640(size); for (uint256 i = start; i < end; i++) { emit TRANSFER336(address(0), to, i); } nextBatch = nextBatch.ADD640(batchSize); _balances[to] = _balances[to].ADD640(size); tokenCount = tokenCount.ADD640(size); return start; } function GETBATCHSTART864(uint256 tokenId) public view returns (uint) { //inject NONSTANDARD NAMING return tokenId.DIV27(batchSize).MUL119(batchSize); } function GETBATCH853(uint256 index) public view returns (uint48 userID, uint16 size) { //inject NONSTANDARD NAMING return (batches[index].userID, batches[index].size); } // Overridden ERC721 functions // @OZ: please stop making variables/functions private function OWNEROF127(uint256 tokenId) //inject NONSTANDARD NAMING public view returns (address) { uint48 uID = ownerIDs[tokenId]; if (uID == 0) { uint256 start = GETBATCHSTART864(tokenId); Batch memory b = batches[start]; require( start + b.size > tokenId, "BT: token does not exist" ); uID = b.userID; require( uID != 0, "BT: bad batch owner" ); } return userIDToAddress[uID]; } function _TRANSFERFROM539( //inject NONSTANDARD NAMING address from, address to, uint256 tokenId ) internal { require( OWNEROF127(tokenId) == from, "BT: transfer of token that is not own" ); require( to != address(0), "BT: transfer to the zero address" ); require( _ISAPPROVEDOROWNER149(msg.sender, tokenId), "BT: caller is not owner nor approved" ); _CANCELAPPROVAL409(tokenId); _balances[from] = _balances[from].SUB596(1); _balances[to] = _balances[to].ADD640(1); ownerIDs[tokenId] = _GETUSERID7(to); emit TRANSFER336(from, to, tokenId); } function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING require( _ISAPPROVEDOROWNER149(msg.sender, tokenId), "BT: caller is not owner nor approved" ); _CANCELAPPROVAL409(tokenId); address owner = OWNEROF127(tokenId); _balances[owner] = _balances[owner].SUB596(1); ownerIDs[tokenId] = 0; tokenCount = tokenCount.SUB596(1); emit TRANSFER336(owner, address(0), tokenId); } function _CANCELAPPROVAL409(uint256 tokenId) internal { //inject NONSTANDARD NAMING if (approvedIDs[tokenId] != 0) { approvedIDs[tokenId] = 0; } } function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF127(tokenId); require( to != owner, "BT: approval to current owner" ); require( msg.sender == owner || ISAPPROVEDFORALL999(owner, msg.sender), "BT: approve caller is not owner nor approved for all" ); approvedIDs[tokenId] = _GETUSERID7(to); emit APPROVAL97(owner, to, tokenId); } function _EXISTS289(uint256 tokenId) //inject NONSTANDARD NAMING internal view returns (bool) { return OWNEROF127(tokenId) != address(0); } function GETAPPROVED252(uint256 tokenId) //inject NONSTANDARD NAMING public view returns (address) { require( _EXISTS289(tokenId), "BT: approved query for nonexistent token" ); return userIDToAddress[approvedIDs[tokenId]]; } function TOTALSUPPLY762() //inject NONSTANDARD NAMING public view returns (uint) { return tokenCount; } function BALANCEOF188(address _owner) //inject NONSTANDARD NAMING public view returns (uint256) { return _balances[_owner]; } } // solium-disable security/no-inline-assembly contract NewCards is Ownable, MultiTransfer, BatchToken, InscribableToken { uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING uint16[] internal cardProtos; uint8[] internal cardQualities; struct Season { uint16 high; uint16 low; } struct Proto { bool locked; bool exists; uint8 god; uint8 cardType; uint8 rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } event PROTOUPDATED864( //inject NONSTANDARD NAMING uint16 indexed id ); event SEASONSTARTED899( //inject NONSTANDARD NAMING uint16 indexed id, string name, uint16 indexed low, uint16 indexed high ); event QUALITYCHANGED816( //inject NONSTANDARD NAMING uint256 indexed tokenId, uint8 quality, address factory ); event CARDSMINTED263( //inject NONSTANDARD NAMING uint256 indexed start, address to, uint16[] protos, uint8[] qualities ); // Value of index proto = season uint16[] public protoToSeason; address public propertyManager; // Array containing all protos Proto[] public protos; // Array containing all seasons Season[] public seasons; // Map whether a season is tradeable or not mapping(uint256 => bool) public seasonTradable; // Map whether a factory has been authorised or not mapping(address => mapping(uint256 => bool)) public factoryApproved; // Whether a factory is approved to create a particular mythic mapping(uint16 => mapping(address => bool)) public mythicApproved; // Whether a mythic is tradable mapping(uint16 => bool) public mythicTradable; // Map whether a mythic exists or not mapping(uint16 => bool) public mythicCreated; uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING constructor( uint256 _batchSize, string memory _name, string memory _symbol ) public BatchToken(_batchSize, _name, _symbol) { cardProtos.length = max_length549; cardQualities.length = max_length549; protoToSeason.length = max_length549; protos.length = max_length549; propertyManager = msg.sender; } function GETDETAILS612( //inject NONSTANDARD NAMING uint256 tokenId ) public view returns (uint16 proto, uint8 quality) { return (cardProtos[tokenId], cardQualities[tokenId]); } function MINTCARD737( //inject NONSTANDARD NAMING address to, uint16 _proto, uint8 _quality ) public returns (uint id) { id = _BATCHMINT199(to, 1); _VALIDATEPROTO247(_proto); cardProtos[id] = _proto; cardQualities[id] = _quality; uint16[] memory ps = new uint16[](1); ps[0] = _proto; uint8[] memory qs = new uint8[](1); qs[0] = _quality; emit CARDSMINTED263(id, to, ps, qs); return id; } function MINTCARDS596( //inject NONSTANDARD NAMING address to, uint16[] memory _protos, uint8[] memory _qualities ) public returns (uint) { require( _protos.length > 0, "Core: must be some protos" ); require( _protos.length == _qualities.length, "Core: must be the same number of protos/qualities" ); uint256 start = _BATCHMINT199(to, uint16(_protos.length)); _VALIDATEANDSAVEDETAILS366(start, _protos, _qualities); emit CARDSMINTED263(start, to, _protos, _qualities); return start; } function ADDFACTORY224( //inject NONSTANDARD NAMING address _factory, uint256 _season ) public ONLYOWNER453 { require( seasons.length >= _season, "Core: season must exist" ); require( _season > 0, "Core: season must not be 0" ); require( !factoryApproved[_factory][_season], "Core: this factory is already approved" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); factoryApproved[_factory][_season] = true; } function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING address _factory, uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "not a mythic" ); require( !mythicApproved[_mythic][_factory], "Core: this factory is already approved for this mythic" ); mythicApproved[_mythic][_factory] = true; } function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "Core: not a mythic" ); require( !mythicTradable[_mythic], "Core: must not be tradable already" ); mythicTradable[_mythic] = true; } function UNLOCKTRADING32( //inject NONSTANDARD NAMING uint256 _season ) public ONLYOWNER453 { require( _season > 0 && _season <= seasons.length, "Core: must be a current season" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); seasonTradable[_season] = true; } function _TRANSFERFROM539( //inject NONSTANDARD NAMING address from, address to, uint256 tokenId ) internal { require( ISTRADABLE528(tokenId), "Core: not yet tradable" ); super._TRANSFERFROM539(from, to, tokenId); } function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING require( ISTRADABLE528(_tokenId), "Core: not yet tradable" ); super._BURN121(_tokenId); } function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING for (uint256 i = 0; i < tokenIDs.length; i++) { BURN6(tokenIDs[i]); } } function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING uint16 proto = cardProtos[_tokenId]; if (proto >= mythic_threshold683) { return mythicTradable[proto]; } return seasonTradable[protoToSeason[proto]]; } function STARTSEASON259( //inject NONSTANDARD NAMING string memory name, uint16 low, uint16 high ) public ONLYOWNER453 returns (uint) { require( low > 0, "Core: must not be zero proto" ); require( high > low, "Core: must be a valid range" ); require( seasons.length == 0 || low > seasons[seasons.length - 1].high, "Core: seasons cannot overlap" ); require( mythic_threshold683 > high, "Core: cannot go into mythic territory" ); // seasons start at 1 uint16 id = uint16(seasons.push(Season({ high: high, low: low }))); uint256 cp; assembly { cp := protoToSeason_slot } StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id); emit SEASONSTARTED899(id, name, low, high); return id; } function UPDATEPROTOS359( //inject NONSTANDARD NAMING uint16[] memory _ids, uint8[] memory _gods, uint8[] memory _cardTypes, uint8[] memory _rarities, uint8[] memory _manas, uint8[] memory _attacks, uint8[] memory _healths, uint8[] memory _tribes ) public ONLYOWNER453 { for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "Core: proto must not be zero" ); Proto memory proto = protos[id]; require( !proto.locked, "Core: proto is locked" ); protos[id] = Proto({ locked: false, exists: true, god: _gods[i], cardType: _cardTypes[i], rarity: _rarities[i], mana: _manas[i], attack: _attacks[i], health: _healths[i], tribe: _tribes[i] }); emit PROTOUPDATED864(id); } } function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING require( _ids.length > 0, "must lock some" ); for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "proto must not be zero" ); Proto storage proto = protos[id]; require( !proto.locked, "proto is locked" ); require( proto.exists, "proto must exist" ); proto.locked = true; emit PROTOUPDATED864(id); } } function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING uint256 start, uint16[] memory _protos, uint8[] memory _qualities ) internal { _VALIDATEPROTOS731(_protos); uint256 cp; assembly { cp := cardProtos_slot } StorageWrite.UINT16S436(cp, start, _protos); uint256 cq; assembly { cq := cardQualities_slot } StorageWrite.UINT8S318(cq, start, _qualities); } function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { uint256 season = protoToSeason[proto]; require( season != 0, "Core: must have season set" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING uint16 maxProto = 0; uint16 minProto = max_uint16315; for (uint256 i = 0; i < _protos.length; i++) { uint16 proto = _protos[i]; if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { if (proto > maxProto) { maxProto = proto; } if (minProto > proto) { minProto = proto; } } } if (maxProto != 0) { uint256 season = protoToSeason[maxProto]; // cards must be from the same season require( season != 0, "Core: must have season set" ); require( season == protoToSeason[minProto], "Core: can only create cards from the same season" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING require( mythicApproved[proto][msg.sender], "Core: not approved to create this mythic" ); require( !mythicCreated[proto], "Core: mythic has already been created" ); mythicCreated[proto] = true; } function SETQUALITY366( //inject NONSTANDARD NAMING uint256 _tokenId, uint8 _quality ) public { uint16 proto = cardProtos[_tokenId]; // wont' be able to change mythic season uint256 season = protoToSeason[proto]; require( factoryApproved[msg.sender][season], "Core: factory can't change quality of this season" ); cardQualities[_tokenId] = _quality; emit QUALITYCHANGED816(_tokenId, _quality, msg.sender); } function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING propertyManager = _manager; } function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETPROPERTY292(_id, _key, _value); } function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETCLASSPROPERTY718(_key, _value); } string public baseURI = "https://api.immutable.com/asset/"; function SETBASEURI249(string memory uri) public ONLYOWNER453 { //inject NONSTANDARD NAMING baseURI = uri; } function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING return string(abi.encodePacked( baseURI, String.FROMADDRESS777(address(this)), "/", String.FROMUINT947(tokenId) )); } } // solium-disable security/no-inline-assembly contract Cards is Ownable, MultiTransfer, BatchToken, ImmutableToken, InscribableToken { uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING uint16[] public cardProtos; uint8[] public cardQualities; struct Season { uint16 high; uint16 low; } struct Proto { bool locked; bool exists; uint8 god; uint8 cardType; uint8 rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } event PROTOUPDATED864( //inject NONSTANDARD NAMING uint16 indexed id ); event SEASONSTARTED899( //inject NONSTANDARD NAMING uint16 indexed id, string name, uint16 indexed low, uint16 indexed high ); event QUALITYCHANGED816( //inject NONSTANDARD NAMING uint256 indexed tokenId, uint8 quality, address factory ); event CARDSMINTED263( //inject NONSTANDARD NAMING uint256 indexed start, address to, uint16[] protos, uint8[] qualities ); // Value of index proto = season uint16[] public protoToSeason; address public propertyManager; // Array containing all protos Proto[] public protos; // Array containing all seasons Season[] public seasons; // Map whether a season is tradeable or not mapping(uint256 => bool) public seasonTradable; // Map whether a factory has been authorised or not mapping(address => mapping(uint256 => bool)) public factoryApproved; // Whether a factory is approved to create a particular mythic mapping(uint16 => mapping(address => bool)) public mythicApproved; // Whether a mythic is tradable mapping(uint16 => bool) public mythicTradable; // Map whether a mythic exists or not mapping(uint16 => bool) public mythicCreated; uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING constructor( uint256 _batchSize, string memory _name, string memory _symbol ) public BatchToken(_batchSize, _name, _symbol) { cardProtos.length = max_length549; cardQualities.length = max_length549; protoToSeason.length = max_length549; protos.length = max_length549; propertyManager = msg.sender; } function GETDETAILS612( //inject NONSTANDARD NAMING uint256 tokenId ) public view returns (uint16 proto, uint8 quality) { return (cardProtos[tokenId], cardQualities[tokenId]); } function MINTCARD737( //inject NONSTANDARD NAMING address to, uint16 _proto, uint8 _quality ) external returns (uint id) { id = _BATCHMINT199(to, 1); _VALIDATEPROTO247(_proto); cardProtos[id] = _proto; cardQualities[id] = _quality; uint16[] memory ps = new uint16[](1); ps[0] = _proto; uint8[] memory qs = new uint8[](1); qs[0] = _quality; emit CARDSMINTED263(id, to, ps, qs); return id; } function MINTCARDS596( //inject NONSTANDARD NAMING address to, uint16[] calldata _protos, uint8[] calldata _qualities ) external returns (uint) { require( _protos.length > 0, "Core: must be some protos" ); require( _protos.length == _qualities.length, "Core: must be the same number of protos/qualities" ); uint256 start = _BATCHMINT199(to, uint16(_protos.length)); _VALIDATEANDSAVEDETAILS366(start, _protos, _qualities); emit CARDSMINTED263(start, to, _protos, _qualities); return start; } function ADDFACTORY224( //inject NONSTANDARD NAMING address _factory, uint256 _season ) public ONLYOWNER453 { require( seasons.length >= _season, "Core: season must exist" ); require( _season > 0, "Core: season must not be 0" ); require( !factoryApproved[_factory][_season], "Core: this factory is already approved" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); factoryApproved[_factory][_season] = true; } function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING address _factory, uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "not a mythic" ); require( !mythicApproved[_mythic][_factory], "Core: this factory is already approved for this mythic" ); mythicApproved[_mythic][_factory] = true; } function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "Core: not a mythic" ); require( !mythicTradable[_mythic], "Core: must not be tradable already" ); mythicTradable[_mythic] = true; } function UNLOCKTRADING32( //inject NONSTANDARD NAMING uint256 _season ) public ONLYOWNER453 { require( _season > 0 && _season <= seasons.length, "Core: must be a current season" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); seasonTradable[_season] = true; } function TRANSFERFROM301( //inject NONSTANDARD NAMING address from, address to, uint256 tokenId ) public { require( ISTRADABLE528(tokenId), "Core: not yet tradable" ); super.TRANSFERFROM301(from, to, tokenId); } function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING require( ISTRADABLE528(_tokenId), "Core: not yet tradable" ); super._BURN121(_tokenId); } function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING for (uint256 i = 0; i < tokenIDs.length; i++) { BURN6(tokenIDs[i]); } } function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING uint16 proto = cardProtos[_tokenId]; if (proto >= mythic_threshold683) { return mythicTradable[proto]; } return seasonTradable[protoToSeason[proto]]; } function STARTSEASON259( //inject NONSTANDARD NAMING string memory name, uint16 low, uint16 high ) public ONLYOWNER453 returns (uint) { require( low > 0, "Core: must not be zero proto" ); require( high > low, "Core: must be a valid range" ); require( seasons.length == 0 || low > seasons[seasons.length - 1].high, "Core: seasons cannot overlap" ); require( mythic_threshold683 > high, "Core: cannot go into mythic territory" ); // seasons start at 1 uint16 id = uint16(seasons.push(Season({ high: high, low: low }))); uint256 cp; assembly { cp := protoToSeason_slot } StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id); emit SEASONSTARTED899(id, name, low, high); return id; } function UPDATEPROTOS359( //inject NONSTANDARD NAMING uint16[] memory _ids, uint8[] memory _gods, uint8[] memory _cardTypes, uint8[] memory _rarities, uint8[] memory _manas, uint8[] memory _attacks, uint8[] memory _healths, uint8[] memory _tribes ) public ONLYOWNER453 { for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "Core: proto must not be zero" ); Proto memory proto = protos[id]; require( !proto.locked, "Core: proto is locked" ); protos[id] = Proto({ locked: false, exists: true, god: _gods[i], cardType: _cardTypes[i], rarity: _rarities[i], mana: _manas[i], attack: _attacks[i], health: _healths[i], tribe: _tribes[i] }); emit PROTOUPDATED864(id); } } function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING require( _ids.length > 0, "must lock some" ); for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "proto must not be zero" ); Proto storage proto = protos[id]; require( !proto.locked, "proto is locked" ); require( proto.exists, "proto must exist" ); proto.locked = true; emit PROTOUPDATED864(id); } } function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING uint256 start, uint16[] memory _protos, uint8[] memory _qualities ) internal { _VALIDATEPROTOS731(_protos); uint256 cp; assembly { cp := cardProtos_slot } StorageWrite.UINT16S436(cp, start, _protos); uint256 cq; assembly { cq := cardQualities_slot } StorageWrite.UINT8S318(cq, start, _qualities); } function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { uint256 season = protoToSeason[proto]; require( season != 0, "Core: must have season set" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING uint16 maxProto = 0; uint16 minProto = max_uint16315; for (uint256 i = 0; i < _protos.length; i++) { uint16 proto = _protos[i]; if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { if (proto > maxProto) { maxProto = proto; } if (minProto > proto) { minProto = proto; } } } if (maxProto != 0) { uint256 season = protoToSeason[maxProto]; // cards must be from the same season require( season != 0, "Core: must have season set" ); require( season == protoToSeason[minProto], "Core: can only create cards from the same season" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING require( mythicApproved[proto][msg.sender], "Core: not approved to create this mythic" ); require( !mythicCreated[proto], "Core: mythic has already been created" ); mythicCreated[proto] = true; } function SETQUALITY366( //inject NONSTANDARD NAMING uint256 _tokenId, uint8 _quality ) public { uint16 proto = cardProtos[_tokenId]; // wont' be able to change mythic season uint256 season = protoToSeason[proto]; require( factoryApproved[msg.sender][season], "Core: factory can't change quality of this season" ); cardQualities[_tokenId] = _quality; emit QUALITYCHANGED816(_tokenId, _quality, msg.sender); } function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING propertyManager = _manager; } function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETPROPERTY292(_id, _key, _value); } function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETCLASSPROPERTY718(_key, _value); } } contract BatchWrapper is NewCards { uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING Cards public old; bool public migrating; constructor( Cards _old, uint256 _batchSize, string memory _name, string memory _symbol ) public NewCards(_batchSize, _name, _symbol) { old = _old; } function SETMIGRATING202(bool _migrating) public ONLYOWNER453 { //inject NONSTANDARD NAMING migrating = _migrating; } function COPYUNTIL891(uint gasThreshold) public { //inject NONSTANDARD NAMING while (gasleft() > gasThreshold) { COPYNEXTBATCH144(); } } function MINTCARDS596(address _to, uint16[] memory _protos, uint8[] memory _qualities) public returns (uint id) { //inject NONSTANDARD NAMING require(!migrating, "must not be migrating"); super.MINTCARDS596(_to, _protos, _qualities); } function MINTCARD737(address _to, uint16 _proto, uint8 _quality) public returns (uint id) { //inject NONSTANDARD NAMING require(!migrating, "must not be migrating"); super.MINTCARD737(_to, _proto, _quality); } // copy all batches from the old contracts // leave ids intact function COPYNEXTBATCH144() public { //inject NONSTANDARD NAMING require(migrating, "must be migrating"); uint256 start = nextBatch; (uint48 userID, uint16 size) = old.batches(start); require(size > 0 && userID > 0, "incorrect batch or limit reached"); if (old.cardProtos(start) != 0) { address to = old.userIDToAddress(userID); uint48 uID = _GETUSERID7(to); batches[start] = Batch({ userID: uID, size: size }); uint256 end = start.ADD640(size); for (uint256 i = start; i < end; i++) { emit TRANSFER336(address(0), to, i); } _balances[to] = _balances[to].ADD640(size); tokenCount = tokenCount.ADD640(size); } nextBatch = nextBatch.ADD640(batchSize); } function ISOLD374(uint _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS289(_tokenId), "card does not exist"); return cardProtos[_tokenId] == 0; } function GETPROTO912(uint _tokenId) public view returns (uint16) { //inject NONSTANDARD NAMING return ISOLD374(_tokenId) ? old.cardProtos(_tokenId) : cardProtos[_tokenId]; } function GETQUALITY41(uint _tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING return ISOLD374(_tokenId) ? old.cardQualities(_tokenId) : cardQualities[_tokenId]; } function GETDETAILS612(uint256 tokenId) public view returns (uint16 proto, uint8 quality) { //inject NONSTANDARD NAMING return ISOLD374(tokenId) ? old.GETDETAILS612(tokenId) : (cardProtos[tokenId], cardQualities[tokenId]); } function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING uint16 proto = GETPROTO912(_tokenId); if (proto >= mythic_threshold683) { return mythicTradable[proto]; } return seasonTradable[protoToSeason[proto]]; } function _TRANSFERFROM539(address from, address to, uint tokenId) internal { //inject NONSTANDARD NAMING require( ISTRADABLE528(tokenId), "BW: not yet tradable" ); super._TRANSFERFROM539(from, to, tokenId); } // update validate protos to check if a proto is 0 // prevent untradable cards function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING uint16 maxProto = 0; uint16 minProto = max_uint16315; for (uint256 i = 0; i < _protos.length; i++) { uint16 proto = _protos[i]; if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { require(proto != 0, "proto is zero"); if (proto > maxProto) { maxProto = proto; } if (minProto > proto) { minProto = proto; } } } if (maxProto != 0) { uint256 season = protoToSeason[maxProto]; // cards must be from the same season require( season != 0, "Core: must have season set" ); require( season == protoToSeason[minProto], "Core: can only create cards from the same season" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } }
inject NONSTANDARD NAMING
function MOD463(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
2,483,432
pragma solidity >=0.8.4; import "./PriceOracle.sol"; import "../root/Root.sol"; import "./StringUtils.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../resolvers/Resolver.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./SafeMath.sol"; /** * @dev A registrar controller for registering and renewing names at fixed cost. */ contract RootRegistrarController is Ownable { using StringUtils for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint constant public MIN_REGISTRATION_DURATION = 31556926; // 1 year uint constant public MAX_REGISTRATION_DURATION = 157784630; // 5 years bytes4 constant private INTERFACE_META_ID = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant private COMMITMENT_CONTROLLER_ID = bytes4( keccak256("rentPrice(string,uint256)") ^ keccak256("available(string)") ^ keccak256("makeCommitment(string,address,bytes32)") ^ keccak256("commit(bytes32)") ^ keccak256("register(string,address,uint256,bytes32)") ^ keccak256("renew(string,uint256)") ); bytes4 constant private COMMITMENT_WITH_CONFIG_CONTROLLER_ID = bytes4( keccak256("registerWithConfig(string,address,uint256,bytes32,address,address)") ^ keccak256("makeCommitmentWithConfig(string,address,bytes32,address,address)") ); Root root; PriceOracle prices; uint public minCommitmentAge; uint public maxCommitmentAge; mapping(bytes32=>uint) public commitments; IERC20 private dWebToken; address approverAddress; uint256 private allowedFeeSlippagePercentage; //Wallet where DWEB fees will go address private dwebDistributorAddress; //Wallet where ETH fees will go address payable private companyWallet; event NameRegistered(string name, bytes32 indexed label, address indexed owner, uint cost, uint expires); event NameRenewed(string name, bytes32 indexed label, uint cost, uint expires); event NewPriceOracle(address indexed oracle); event DecentraWebDistributorChanged(address indexed dwebDistributorAddress); event CompanyWalletChanged(address indexed wallet); // modifiers modifier onlyContract(address account) { require(account.isContract(), "[Validation] The address does not contain a contract"); _; } constructor(Root _root, PriceOracle _prices, IERC20 _dWebToken, address _dwebDistributorAddress, address payable _companyWallet, uint _minCommitmentAge, uint _maxCommitmentAge) { require(_maxCommitmentAge > _minCommitmentAge); root = _root; prices = _prices; dWebToken = _dWebToken; dwebDistributorAddress = _dwebDistributorAddress; companyWallet = _companyWallet; minCommitmentAge = _minCommitmentAge; maxCommitmentAge = _maxCommitmentAge; allowedFeeSlippagePercentage = 5; } // pure or view methods // Actual price is returned. Any additional cost/price slippage should be taken care by front end when sending tx // Returned price is in wei or ERC20 token decimal // Duration is in seconds function rentPrice(string memory name, uint duration, bool isFeeInDWEBToken) view public returns(uint256) { bytes32 label = keccak256(bytes(name)); bytes32 tokenId = keccak256(abi.encodePacked(root.rootNode(), label)); return prices.price(name, root.nameExpires(uint256(tokenId)), duration, isFeeInDWEBToken, address(dWebToken)); } function valid(string memory name) public pure returns(bool) { return name.strlen() >= 3; } function available(string memory name) public view returns(bool) { bytes32 label = keccak256(bytes(name)); bytes32 tokenId = keccak256(abi.encodePacked(root.rootNode(), label)); return valid(name) && root.available(uint256(tokenId)); } function makeCommitment(string memory name, address owner, bytes32 secret) pure public returns(bytes32) { return makeCommitmentWithConfig(name, owner, secret, address(0), address(0)); } function makeCommitmentWithConfig(string memory name, address owner, bytes32 secret, address resolver, address addr) pure public returns(bytes32) { bytes32 label = keccak256(bytes(name)); if (resolver == address(0) && addr == address(0)) { return keccak256(abi.encodePacked(label, owner, secret)); } require(resolver != address(0)); return keccak256(abi.encodePacked(label, owner, resolver, addr, secret)); } function supportsInterface(bytes4 interfaceID) external pure returns (bool) { return interfaceID == INTERFACE_META_ID || interfaceID == COMMITMENT_CONTROLLER_ID || interfaceID == COMMITMENT_WITH_CONFIG_CONTROLLER_ID; } // internal methods function _consumeCommitment(string memory name, uint duration, bytes32 commitment) internal returns (uint256) { // Require a valid commitment require(commitments[commitment] + minCommitmentAge <= block.timestamp); // If the commitment is too old, or the name is registered, stop require(commitments[commitment] + maxCommitmentAge > block.timestamp); require(available(name)); delete(commitments[commitment]); require(duration >= MIN_REGISTRATION_DURATION); require(duration <= MAX_REGISTRATION_DURATION); } // modifier protected methods function setPriceOracle(PriceOracle _prices) public onlyOwner { prices = _prices; emit NewPriceOracle(address(prices)); } function setCommitmentAges(uint _minCommitmentAge, uint _maxCommitmentAge) public onlyOwner { minCommitmentAge = _minCommitmentAge; maxCommitmentAge = _maxCommitmentAge; } function withdraw() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } function setApproverAddress(address _approver) external onlyOwner { approverAddress = _approver; } function setDecentraWebDistributor(address _dwebDistributorAddress) external onlyOwner onlyContract(dwebDistributorAddress) { require( _dwebDistributorAddress != address(0), "[Validation] dwebDistributorAddress is the zero address" ); dwebDistributorAddress = _dwebDistributorAddress; emit DecentraWebDistributorChanged(_dwebDistributorAddress); } function setCompanyWallet(address payable wallet) external onlyOwner { require( wallet != address(0), "[Validation] wallet is the zero address" ); companyWallet = wallet; emit CompanyWalletChanged(wallet); } // public or external methods function commit(bytes32 commitment, uint8 v, bytes32 r, bytes32 s) public { require(commitments[commitment] + maxCommitmentAge < block.timestamp); // name must be approved by approver address //TODO-release: uncomment below block /* address signer = ecrecover(commitment, v, r, s); require(signer == approverAddress, "commit: invalid signature"); require(signer != address(0), "ECDSA: invalid signature"); */ commitments[commitment] = block.timestamp; } function register(string calldata name, address owner, uint duration, bytes32 secret, bool isFeeInDWEBToken, uint256 fee) external payable { registerWithConfig(name, owner, duration, secret, address(0), address(0), isFeeInDWEBToken, fee); } // fee must be passed in decimal // name must be TLD. It should not contain dot(.) function registerWithConfig(string memory name, address owner, uint duration, bytes32 secret, address resolver, address addr, bool isFeeInDWEBToken, uint256 fee) public payable { // TODO: name has to be TLD. put check for this bytes32 commitment = makeCommitmentWithConfig(name, owner, secret, resolver, addr); _consumeCommitment(name, duration, commitment); uint256 cost = rentPrice(name, duration, isFeeInDWEBToken); bytes32 label = keccak256(bytes(name)); // The nodehash of this label bytes32 tokenId = keccak256(abi.encodePacked(root.rootNode(), label)); uint expires; // TODO-enhancement : skipping setting records for now // --- // if(resolver != address(0)) { // // Set this contract as the (temporary) owner, giving it // // permission to set up the resolver. // expires = root.register(uint256(tokenId), address(this), duration); // // Set the resolver // root.ens().setResolver(tokenId, resolver); // // Configure the resolver // if (addr != address(0)) { // Resolver(resolver).setAddr(tokenId, addr); // } // // Now transfer full ownership to the expeceted owner // //base.reclaim(tokenId, owner); // //base.transferFrom(address(this), owner, tokenId); // // TODO: can we improve below? // root.decentraNameController().decentraName().safeTransferFrom(address(this), owner, uint256(tokenId)); // } else // --- { require(addr == address(0)); expires = root.register(uint256(tokenId), owner, duration); } // Process payment if(isFeeInDWEBToken) { // TODO-review: do we really need to fail the tx // uint256 feeDiff = 0; // if( fee < cost ) { // feeDiff = cost.sub(fee); // uint256 feeSlippagePercentage = feeDiff.mul(100).div(cost); // //will allow if diff is less than 5% // require(feeSlippagePercentage < allowedFeeSlippagePercentage, "[Validation] Fee (DWEB) is below minimum required fee"); // } require(fee >= cost, "[Validation] Enough DWEB not sent"); // TODO-reivew it will throw if tx is failed dWebToken.safeTransferFrom(msg.sender, dwebDistributorAddress, cost); } else { require(msg.value >= cost, "[Validation] Enough ETH not sent"); // TODO-review : we still need to refund right? (bool success,) = companyWallet.call{value: cost}(""); require(success, "[Validation] Transfer of fee failed"); // Refund any extra payment if(msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); } } emit NameRegistered(name, label, owner, cost, expires); } function renew(string calldata name, uint duration, bool isFeeInDWEBToken) external payable { // TODO: manage total duration should be between 1 year and 5 years // TODO: payment processing in dweb pending uint256 cost = rentPrice(name, duration, isFeeInDWEBToken); require(msg.value >= cost); bytes32 label = keccak256(bytes(name)); bytes32 tokenId = keccak256(abi.encodePacked(root.rootNode(), label)); uint expires = root.renew(uint256(tokenId), duration); if(msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); } emit NameRenewed(name, label, cost, expires); } }
TODO: manage total duration should be between 1 year and 5 years TODO: payment processing in dweb pending
function renew(string calldata name, uint duration, bool isFeeInDWEBToken) external payable { uint256 cost = rentPrice(name, duration, isFeeInDWEBToken); require(msg.value >= cost); bytes32 label = keccak256(bytes(name)); bytes32 tokenId = keccak256(abi.encodePacked(root.rootNode(), label)); uint expires = root.renew(uint256(tokenId), duration); if(msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); } emit NameRenewed(name, label, cost, expires); }
12,743,615
pragma solidity 0.4.24; import "./PumaPayToken.sol"; import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @title PumaPayVault - Contract that will hold PMA locked for a specific period of time with predefined withdrawal windows for a certain percentage of tokens. /// @author Giorgos Kourtellos - <giorgos@pumapay.io> contract PumaPayVault is Ownable { using SafeMath for uint256; /// ================================================================================================================= /// Events /// ================================================================================================================= event LogWithdraw(uint256 amount); event LogNextUnlockTimestamp(uint256 nextUnlockedTimestamp); event LogTokensAllowedForWithdrawal(uint256 tokensAllowedForWithdrawal); /// ================================================================================================================= /// Constants /// ================================================================================================================= uint256 constant public UNLOCKED_PERIOD = 2 days; /// ================================================================================================================= /// Members /// ================================================================================================================= uint256 public nextUnlockedTimestamp; uint256 public amountOfTokensAllowedForWithdrawal; uint256 public amountOfTokensWithdrawn; bool public lockedScheduleConstructed; uint256[] public intervals; uint256[] public percentages; PumaPayToken public token; struct LockScheduleDetails { uint256 unlockStartTime; uint256 unlockedAmount; } LockScheduleDetails[] public lockSchedule; /// ================================================================================================================= /// Modifiers /// ================================================================================================================= modifier hasTokens() { require(token.balanceOf(this) > 0); _; } modifier lockedScheduleNOTConstructed() { require(!lockedScheduleConstructed); _; } modifier lockedScheduleISConstructed() { require(lockedScheduleConstructed); _; } modifier isUnlocked() { require(vaultIsUnlocked()); _; } modifier isLocked() { require(!vaultIsUnlocked()); _; } modifier validAmountOfTokens(uint256 amount) { require(amountOfTokensAllowedForWithdrawal >= amount); _; } modifier lastValueOfArrayIs100(uint256[] arrayOfNumbers) { require(arrayOfNumbers[arrayOfNumbers.length - 1] == 100); _; } modifier validRequirements(address _owner, PumaPayToken _token, uint256[] _intervals, uint256[] _percentages) { require( _owner != address(0) && _token != address(0) && _intervals.length == _percentages.length && validIntervals(_intervals) && validPercentages(_percentages) ); _; } /// ================================================================================================================= /// Constructor /// ================================================================================================================= /// @dev Contract constructor sets owner of the vault, the intervals on which the vault will be unlocked /// and the percentages of the vault that will be unlocked for the certain intervals /// @param _owner Owner of the Vault. /// @param _tokenAddress Token Address. /// @param _intervals Intervals in days on which the vault will be unlocked. /// @param _percentages Percentage of the tokens held by the vault that are unlocked over the specified intervals. constructor(address _owner, PumaPayToken _tokenAddress, uint256[] _intervals, uint256[] _percentages) public validRequirements(_owner, _tokenAddress, _intervals, _percentages) { lockedScheduleConstructed = false; token = _tokenAddress; owner = _owner; intervals = _intervals; percentages = _percentages; } // ================================================================================================================= // Public Functions // ================================================================================================================= /// @dev Allows for withdrawing tokens from the vault - it can be executed only by the owner and only when the locked schedule is constructed /// the vault must be ulocked, to hold the amount of tokens the owner requests and to be within the allowed token amount /// The tokens are transfered to the owner account /// @param _amountOfTokens - number of tokens to be withrawn function withdrawTokens(uint256 _amountOfTokens) public onlyOwner() lockedScheduleISConstructed() isUnlocked() validAmountOfTokens(_amountOfTokens) { token.transfer(owner, _amountOfTokens); amountOfTokensWithdrawn = amountOfTokensWithdrawn + _amountOfTokens; amountOfTokensAllowedForWithdrawal = amountOfTokensAllowedForWithdrawal.sub(_amountOfTokens); emit LogWithdraw(_amountOfTokens); emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal); } /// @dev Sets the next withrawal details i.e. unclocked timestamp and amount of tokens can be executed only by the owner of the vault /// and only after the lock schedule has been constructed and the vault is not locked function setNextWithdrawalDetails() public onlyOwner() isLocked() lockedScheduleISConstructed() { for (uint i = 0; i < lockSchedule.length; i++) { if (lockSchedule[i].unlockStartTime > now) { nextUnlockedTimestamp = lockSchedule[i].unlockStartTime; amountOfTokensAllowedForWithdrawal = lockSchedule[i].unlockedAmount - amountOfTokensWithdrawn; emit LogNextUnlockTimestamp(nextUnlockedTimestamp); emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal); return; } } } /// @dev Constructs the LockDownSchedule mapping only once and only if the vault holds tokens /// can be executed only by the owner of the vault function constructLockedDownSchedule() public onlyOwner() hasTokens() lockedScheduleNOTConstructed() { for (uint i = 0; i < intervals.length; i++) { lockSchedule.push( LockScheduleDetails({ unlockStartTime: now + (intervals[i] * 24 * 60 * 60), unlockedAmount: token.balanceOf(this) * percentages[i] / 100 }) ); } amountOfTokensWithdrawn = 0; nextUnlockedTimestamp = lockSchedule[0].unlockStartTime; amountOfTokensAllowedForWithdrawal = lockSchedule[0].unlockedAmount; lockedScheduleConstructed = true; emit LogNextUnlockTimestamp(nextUnlockedTimestamp); emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal); } function vaultIsUnlocked() public view returns (bool) { return (now > nextUnlockedTimestamp && now < nextUnlockedTimestamp + UNLOCKED_PERIOD); } // ================================================================================================================= // Internal Functions // ================================================================================================================= /// Checks if the intervals specified in contract creation are valid /// Valid means that each interval should be higher than the previous one and none should be zero /// @param _intervals - array of intervals initiating the contract function validIntervals(uint256[] _intervals) internal pure returns(bool) { uint256 previousInterval = 0; for (uint i = 0; i < _intervals.length; i++) { if (_intervals[i] <= 0 || _intervals[i] < previousInterval) { return false; } previousInterval = _intervals[i]; } return true; } /// Checks if the percentages specified in contract creation are valid /// Valid means that each percentages should be higher than the previous one and none should be zero /// Also the last value of the array should be 100, otherwise there will be locked tokens with no way of retrieving them /// @param _percentages - array of percentages initiating the contract function validPercentages(uint256[] _percentages) internal pure lastValueOfArrayIs100(_percentages) returns(bool) { uint256 previousPercentage = 0; for (uint i = 0; i < _percentages.length; i++) { if (_percentages[i] <= 0 || _percentages[i] < previousPercentage) { return false; } previousPercentage = _percentages[i]; } return true; } }
Sets the next withrawal details i.e. unclocked timestamp and amount of tokens can be executed only by the owner of the vault and only after the lock schedule has been constructed and the vault is not locked
function setNextWithdrawalDetails() public onlyOwner() isLocked() lockedScheduleISConstructed() { for (uint i = 0; i < lockSchedule.length; i++) { if (lockSchedule[i].unlockStartTime > now) { nextUnlockedTimestamp = lockSchedule[i].unlockStartTime; amountOfTokensAllowedForWithdrawal = lockSchedule[i].unlockedAmount - amountOfTokensWithdrawn; emit LogNextUnlockTimestamp(nextUnlockedTimestamp); emit LogTokensAllowedForWithdrawal(amountOfTokensAllowedForWithdrawal); return; } } }
5,474,107
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../lib/LibOrder.sol"; import "../lib/LibTypes.sol"; import "../lib/LibMath.sol"; import "./MarginAccount.sol"; contract Perpetual is MarginAccount, ReentrancyGuard { using LibMathSigned for int256; using LibMathUnsigned for uint256; using LibOrder for LibTypes.Side; uint256 public totalAccounts; address[] public accountList; mapping(address => bool) private accountCreated; event CreatePerpetual(); event Paused(address indexed caller); event Unpaused(address indexed caller); event DisableWithdraw(address indexed caller); event EnableWithdraw(address indexed caller); event CreateAccount(uint256 indexed id, address indexed trader); event Trade(address indexed trader, LibTypes.Side side, uint256 price, uint256 amount); event Liquidate(address indexed keeper, address indexed trader, uint256 price, uint256 amount); event EnterEmergencyStatus(uint256 price); event EnterSettledStatus(uint256 price); constructor( address _globalConfig, address _devAddress, address _collateral, uint256 _collateralDecimals ) MarginAccount(_globalConfig, _collateral, _collateralDecimals) { devAddress = _devAddress; emit CreatePerpetual(); } // disable fallback fallback() external payable { revert("fallback function disabled"); } /** * @dev Called by a pauseControllers, put whole system into paused state. */ function pause() external { require( globalConfig.pauseControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(!paused, "already paused"); paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauseControllers, put whole system back to normal. */ function unpause() external { require( globalConfig.pauseControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(paused, "not paused"); paused = false; emit Unpaused(msg.sender); } /** * @dev Called by a withdrawControllers disable withdraw function. */ function disableWithdraw() external { require( globalConfig.withdrawControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(!withdrawDisabled, "already disabled"); withdrawDisabled = true; emit DisableWithdraw(msg.sender); } /** * @dev Called by a withdrawControllers, enable withdraw function again. */ function enableWithdraw() external { require( globalConfig.withdrawControllers(msg.sender) || globalConfig.owner() == msg.sender, "unauthorized caller" ); require(withdrawDisabled, "not disabled"); withdrawDisabled = false; emit EnableWithdraw(msg.sender); } /** * @notice Force to set cash balance of margin account. Called by administrator to * fix unexpected cash balance. * * @param trader Address of account owner. * @param amount Absolute cash balance value to be set. */ function increaseCashBalance(address trader, uint256 amount) external onlyOwner { require(status == LibTypes.Status.EMERGENCY, "wrong perpetual status"); updateCashBalance(trader, amount.toInt256()); } /** * @notice Force to set cash balance of margin account. Called by administrator to * fix unexpected cash balance. * * @param trader Address of account owner. * @param amount Absolute cash balance value to be set. */ function decreaseCashBalance(address trader, uint256 amount) external onlyOwner { require(status == LibTypes.Status.EMERGENCY, "wrong perpetual status"); updateCashBalance(trader, amount.toInt256().neg()); } /** * @notice Set perpetual status to 'emergency'. It can be called multiple times to set price. * In emergency mode, main function like trading / withdrawing is disabled to prevent unexpected loss. * * @param price Price used as mark price in emergency mode. */ function beginGlobalSettlement(uint256 price) external onlyOwner { require(status != LibTypes.Status.SETTLED, "wrong perpetual status"); status = LibTypes.Status.EMERGENCY; settlementPrice = price; emit EnterEmergencyStatus(price); } /** * @notice Set perpetual status to 'settled'. It can be call only once in 'emergency' mode. * In settled mode, user is expected to closed positions and withdraw all the collateral. */ function endGlobalSettlement() external onlyOwner { require(status == LibTypes.Status.EMERGENCY, "wrong perpetual status"); status = LibTypes.Status.SETTLED; emit EnterSettledStatus(settlementPrice); } /** * @notice Deposit collateral to insurance fund to recover social loss. Note that depositing to * insurance fund *DOES NOT* profit to depositor and only administrator can withdraw from the fund. * * @param rawAmount Amount to deposit. */ function depositToInsuranceFund(uint256 rawAmount) external payable nonReentrant { checkDepositingParameter(rawAmount); require(rawAmount > 0, "amount must be greater than 0"); int256 wadAmount = pullCollateral(msg.sender, rawAmount); insuranceFundBalance = insuranceFundBalance.add(wadAmount); require(insuranceFundBalance >= 0, "negtive insurance fund"); emit UpdateInsuranceFund(insuranceFundBalance); } /** * @notice Withdraw collateral from insurance fund. Only administrator can withdraw from it. * * @param rawAmount Amount to withdraw. */ function withdrawFromInsuranceFund(uint256 rawAmount) external onlyOwner nonReentrant { require(rawAmount > 0, "amount must be greater than 0"); require(insuranceFundBalance > 0, "insufficient funds"); int256 wadAmount = toWad(rawAmount); require(wadAmount <= insuranceFundBalance, "insufficient funds"); insuranceFundBalance = insuranceFundBalance.sub(wadAmount); pushCollateral(msg.sender, rawAmount); require(insuranceFundBalance >= 0, "negtive insurance fund"); emit UpdateInsuranceFund(insuranceFundBalance); } // End Admin functions // Deposit && Withdraw /** * @notice Deposit collateral to sender's margin account. * When depositing ether rawAmount must strictly equal to * * @dev Need approval * * @param rawAmount Amount to deposit. */ function deposit(uint256 rawAmount) external payable { depositImplementation(msg.sender, rawAmount); } /** * @notice Withdraw collateral from sender's margin account. only available in normal state. * * @param rawAmount Amount to withdraw. */ function withdraw(uint256 rawAmount) external { withdrawImplementation(msg.sender, rawAmount); } /** * @notice Close all position and withdraw all collateral remaining in sender's margin account. * Settle is only available in settled state and can be called multiple times. */ function settle() external nonReentrant { address payable trader = msg.sender; settleImplementation(trader); int256 wadAmount = marginAccounts[trader].cashBalance; if (wadAmount <= 0) { return; } uint256 rawAmount = toCollateral(wadAmount); Collateral.withdraw(trader, rawAmount); } // Deposit && Withdraw - Whitelisted Only /** * @notice Deposit collateral for trader into the trader's margin account. The collateral will be transfer * from the trader's ethereum address. * depositFor is only available to administrator. * * @dev Need approval * * @param trader Address of margin account to deposit into. * @param rawAmount Amount of collateral to deposit. */ function depositFor(address trader, uint256 rawAmount) external payable onlyAuthorized { depositImplementation(trader, rawAmount); } /** * @notice Withdraw collateral for trader from the trader's margin account. The collateral will be transfer * to the trader's ethereum address. * withdrawFor is only available to administrator. * * @param trader Address of margin account to deposit into. * @param rawAmount Amount of collateral to deposit. */ function withdrawFor(address payable trader, uint256 rawAmount) external onlyAuthorized { withdrawImplementation(trader, rawAmount); } // Method for public properties /** * @notice Price to calculate all price-depended properties of margin account. * * @dev decimals == 18 * * @return Mark price. */ function markPrice() public returns (uint256) { return status == LibTypes.Status.NORMAL ? fundingModule.currentMarkPrice() : settlementPrice; } /** * @notice (initial) Margin value of margin account according to mark price. * See marginWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Initial margin of margin account. */ function positionMargin(address trader) public returns (uint256) { return MarginAccount.marginWithPrice(trader, markPrice()); } /** * @notice (maintenance) Margin value of margin account according to mark price. * See maintenanceMarginWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Maintanence margin of margin account. */ function maintenanceMargin(address trader) public returns (uint256) { return MarginAccount.maintenanceMarginWithPrice(trader, markPrice()); } /** * @notice Margin balance of margin account according to mark price. * See marginBalanceWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Margin balance of margin account. */ function marginBalance(address trader) public returns (int256) { return MarginAccount.marginBalanceWithPrice(trader, markPrice()); } /** * @notice Profit and loss of margin account according to mark price. * See pnlWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Margin balance of margin account. */ function pnl(address trader) public returns (int256) { return MarginAccount.pnlWithPrice(trader, markPrice()); } /** * @notice Available margin of margin account according to mark price. * See marginBalanceWithPrice in MarginAccount.sol. * * @param trader Address of account owner. * @return Margin balance of margin account. */ function availableMargin(address trader) public returns (int256) { return MarginAccount.availableMarginWithPrice(trader, markPrice()); } /** * @notice Test if a margin account is safe, using maintenance margin rate. * A unsafe margin account will loss position through liqudating initiated by any other trader, to make the whole system safe. * * @param trader Address of account owner. * @return True if give trader is safe. */ function isSafe(address trader) public returns (bool) { uint256 currentMarkPrice = markPrice(); return isSafeWithPrice(trader, currentMarkPrice); } /** * @notice Test if a margin account is safe, using maintenance margin rate according to given price. * * @param trader Address of account owner. * @param currentMarkPrice Mark price. * @return True if give trader is safe. */ function isSafeWithPrice(address trader, uint256 currentMarkPrice) public returns (bool) { return MarginAccount.marginBalanceWithPrice(trader, currentMarkPrice) >= MarginAccount.maintenanceMarginWithPrice(trader, currentMarkPrice).toInt256(); } /** * @notice Test if a margin account is bankrupt. Bankrupt is a status indicates the margin account * is completely out of collateral. * * @param trader Address of account owner. * @return True if give trader is safe. */ function isBankrupt(address trader) public returns (bool) { return marginBalanceWithPrice(trader, markPrice()) < 0; } /** * @notice Test if a margin account is safe, using initial margin rate instead of maintenance margin rate. * * @param trader Address of account owner. * @return True if give trader is safe with initial margin rate. */ function isIMSafe(address trader) public returns (bool) { uint256 currentMarkPrice = markPrice(); return isIMSafeWithPrice(trader, currentMarkPrice); } /** * @notice Test if a margin account is safe according to given mark price. * * @param trader Address of account owner. * @param currentMarkPrice Mark price. * @return True if give trader is safe with initial margin rate. */ function isIMSafeWithPrice(address trader, uint256 currentMarkPrice) public returns (bool) { return availableMarginWithPrice(trader, currentMarkPrice) >= 0; } /** * @notice Test if a margin account is safe according to given mark price. * * @param trader Address of account owner. * @param maxAmount Mark price. * @return True if give trader is safe with initial margin rate. */ function liquidate( address trader, uint256 maxAmount ) public onlyNotPaused returns (uint256, uint256) { require(msg.sender != trader, "self liquidate"); require(isValidLotSize(maxAmount), "amount must be divisible by lotSize"); require(status != LibTypes.Status.SETTLED, "wrong perpetual status"); require(!isSafe(trader), "safe account"); uint256 liquidationPrice = markPrice(); require(liquidationPrice > 0, "price must be greater than 0"); uint256 liquidationAmount = calculateLiquidateAmount(trader, liquidationPrice); uint256 totalPositionSize = marginAccounts[trader].size; uint256 liquidatableAmount = totalPositionSize.sub(totalPositionSize.mod(governance.lotSize)); liquidationAmount = liquidationAmount.ceil(governance.lotSize).min(maxAmount).min(liquidatableAmount); require(liquidationAmount > 0, "nothing to liquidate"); uint256 opened = MarginAccount.liquidate(msg.sender, trader, liquidationPrice, liquidationAmount); if (opened > 0) { require(availableMarginWithPrice(msg.sender, liquidationPrice) >= 0, "liquidator margin"); } else { require(isSafe(msg.sender), "liquidator unsafe"); } emit Liquidate(msg.sender, trader, liquidationPrice, liquidationAmount); return (liquidationPrice, liquidationAmount); } function tradePosition( address taker, address maker, LibTypes.Side side, uint256 price, uint256 amount ) public onlyNotPaused onlyAuthorized returns (uint256 takerOpened, uint256 makerOpened) { require(status != LibTypes.Status.EMERGENCY, "wrong perpetual status"); require(side == LibTypes.Side.LONG || side == LibTypes.Side.SHORT, "side must be long or short"); require(isValidLotSize(amount), "amount must be divisible by lotSize"); takerOpened = MarginAccount.trade(taker, side, price, amount); makerOpened = MarginAccount.trade(maker, LibTypes.counterSide(side), price, amount); require(totalSize(LibTypes.Side.LONG) == totalSize(LibTypes.Side.SHORT), "imbalanced total size"); emit Trade(taker, side, price, amount); emit Trade(maker, LibTypes.counterSide(side), price, amount); } function transferCashBalance( address from, address to, uint256 amount ) public onlyNotPaused onlyAuthorized { require(status != LibTypes.Status.EMERGENCY, "wrong perpetual status"); MarginAccount.transferBalance(from, to, amount.toInt256()); } function registerNewTrader(address trader) internal { emit CreateAccount(totalAccounts, trader); accountList.push(trader); totalAccounts++; accountCreated[trader] = true; } /** * @notice Check type of collateral. If ether, rawAmount must strictly match msg.value. * * @param rawAmount Amount to deposit */ function checkDepositingParameter(uint256 rawAmount) internal view { bool isToken = isTokenizedCollateral(); require((isToken && msg.value == 0) || (!isToken && msg.value == rawAmount), "incorrect sent value"); } /** * @notice Implementation as underlaying of deposit and depositFor. * * @param trader Address the collateral will be transferred from. * @param rawAmount Amount to deposit. */ function depositImplementation(address trader, uint256 rawAmount) internal onlyNotPaused nonReentrant { checkDepositingParameter(rawAmount); require(rawAmount > 0, "amount must be greater than 0"); require(trader != address(0), "cannot deposit to 0 address"); Collateral.deposit(trader, rawAmount); // append to the account list. make the account trackable if (!accountCreated[trader]) { registerNewTrader(trader); } } /** * @notice Implementation as underlaying of withdraw and withdrawFor. * * @param trader Address the collateral will be transferred to. * @param rawAmount Amount to withdraw. */ function withdrawImplementation(address payable trader, uint256 rawAmount) internal onlyNotPaused nonReentrant { require(!withdrawDisabled, "withdraw disabled"); require(status == LibTypes.Status.NORMAL, "wrong perpetual status"); require(rawAmount > 0, "amount must be greater than 0"); require(trader != address(0), "cannot withdraw to 0 address"); uint256 currentMarkPrice = markPrice(); require(isSafeWithPrice(trader, currentMarkPrice), "unsafe before withdraw"); remargin(trader, currentMarkPrice); Collateral.withdraw(trader, rawAmount); require(isSafeWithPrice(trader, currentMarkPrice), "unsafe after withdraw"); require(availableMarginWithPrice(trader, currentMarkPrice) >= 0, "withdraw margin"); } /** * @notice Implementation as underlaying of settle. * * @param trader Address the collateral will be transferred to. */ function settleImplementation(address trader) internal onlyNotPaused { require(status == LibTypes.Status.SETTLED, "wrong perpetual status"); uint256 currentMarkPrice = markPrice(); LibTypes.MarginAccount memory account = marginAccounts[trader]; if (account.size == 0) { return; } LibTypes.Side originalSide = account.side; close(account, currentMarkPrice, account.size); marginAccounts[trader] = account; emit UpdatePositionAccount(trader, account, totalSize(originalSide), currentMarkPrice); } function setFairPrice(uint256 price) public onlyAuthorized { fundingModule.setFairPrice(price); } }
trader Address of account owner. return True if give trader is safe./
function isSafe(address trader) public returns (bool) { uint256 currentMarkPrice = markPrice(); return isSafeWithPrice(trader, currentMarkPrice); }
5,536,059
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; 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); } library SafeMathUpgradeable { /** * @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; } } 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 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); } } } } library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; 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).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(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"); } } } abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } 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 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; } uint256[50] private __gap; } 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 initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * 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()); } uint256[49] private __gap; } contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } interface IController { function withdraw(address, uint256) external; function withdrawAll(address) external; function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function approveStrategy(address, address) external; function setStrategy(address, address) external; function setVault(address, address) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function balanceOfPool() external view returns (uint256); function balanceOfWant() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function controller() external returns (address); function governance() external returns (address); function tend() external; function harvest() external; } abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } function isProtectedToken(address token) public view returns (bool) { address[] memory protectedTokens = getProtectedTokens(); for (uint256 i = 0; i < protectedTokens.length; i++) { if (token == protectedTokens[i]) { return true; } } return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() public virtual view returns (address[] memory) { return new address[](0); } /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } contract BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } } interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } contract UniswapSwapper is BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address internal constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router function _swapExactTokensForTokens( address router, address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, router, balance); IUniswapRouterV2(router).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapExactETHForTokens( address router, uint256 balance, address[] memory path ) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapExactTokensForETH( address router, address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, router, balance); IUniswapRouterV2(router).swapExactTokensForETH(balance, 0, path, address(this), now); } function _getPair( address router, address token0, address token1 ) internal view returns (address) { address factory = IUniswapRouterV2(router).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _addMaxLiquidity( address router, address token0, address token1 ) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, router, _token0Balance); _safeApproveHelper(token1, router, _token1Balance); IUniswapRouterV2(router).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _addMaxLiquidityEth(address router, address token0) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _ethBalance = address(this).balance; _safeApproveHelper(token0, router, _token0Balance); IUniswapRouterV2(router).addLiquidityETH{value: address(this).balance}(token0, _token0Balance, 0, 0, address(this), block.timestamp); } } interface IUnitVaultParameters { function tokenDebtLimit(address asset) external view returns (uint256); } interface IUnitVault { function calculateFee( address asset, address user, uint256 amount ) external view returns (uint256); function getTotalDebt(address asset, address user) external view returns (uint256); function debts(address asset, address user) external view returns (uint256); function collaterals(address asset, address user) external view returns (uint256); function tokenDebts(address asset) external view returns (uint256); } interface IUnitCDPManager { function exit( address asset, uint256 assetAmount, uint256 usdpAmount ) external returns (uint256); function join( address asset, uint256 assetAmount, uint256 usdpAmount ) external; function oracleRegistry() external view returns (address); } interface IUnitUsdOracle { // returns Q112-encoded value // returned value 10**18 * 2**112 is $1 function assetToUsd(address asset, uint256 amount) external view returns (uint256); } interface IUnitOracleRegistry { function oracleByAsset(address asset) external view returns (address); } abstract contract StrategyUnitProtocolMeta is BaseStrategy, UniswapSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; // Unit Protocol module: https://github.com/unitprotocol/core/blob/master/CONTRACTS.md address public constant cdpMgr01 = 0x0e13ab042eC5AB9Fc6F43979406088B9028F66fA; address public constant unitVault = 0xb1cFF81b9305166ff1EFc49A129ad2AfCd7BCf19; address public constant unitVaultParameters = 0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D; address public constant debtToken = 0x1456688345527bE1f37E9e627DA0837D6f08C925; address public constant eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; bool public useUnitUsdOracle = true; // sub-strategy related constants address public collateral; uint256 public collateralDecimal = 1e18; address public unitOracle; uint256 public collateralPriceDecimal = 1; bool public collateralPriceEth = false; // configurable minimum collateralization percent this strategy would hold for CDP uint256 public minRatio = 150; // collateralization percent buffer in CDP debt actions uint256 public ratioBuff = 200; uint256 public constant ratioBuffMax = 10000; // used as dust to avoid closing out a debt repayment uint256 public dustMinDebt = 10000; uint256 public constant Q112 = 2**112; // **** Modifiers **** // function _onlyCDPInUse() internal view { uint256 collateralAmt = getCollateralBalance(); require(collateralAmt > 0, "!zeroCollateral"); uint256 debtAmt = getDebtBalance(); require(debtAmt > 0, "!zeroDebt"); } // **** Getters **** function getCollateralBalance() public view returns (uint256) { return IUnitVault(unitVault).collaterals(collateral, address(this)); } function getDebtBalance() public view returns (uint256) { return IUnitVault(unitVault).getTotalDebt(collateral, address(this)); } function getDebtWithoutFee() public view returns (uint256) { return IUnitVault(unitVault).debts(collateral, address(this)); } function getDueFee() public view returns (uint256) { uint256 totalDebt = getDebtBalance(); uint256 borrowed = getDebtWithoutFee(); return totalDebt > borrowed? totalDebt.sub(borrowed) : 0; } function debtLimit() public view returns (uint256) { return IUnitVaultParameters(unitVaultParameters).tokenDebtLimit(collateral); } function debtUsed() public view returns (uint256) { return IUnitVault(unitVault).tokenDebts(collateral); } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public override view returns (uint256) { return getCollateralBalance(); } function collateralValue(uint256 collateralAmt) public view returns (uint256) { uint256 collateralPrice = getLatestCollateralPrice(); return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal); // debtToken in 1e18 decimal } function currentRatio() public view returns (uint256) { _onlyCDPInUse(); uint256 collateralAmt = collateralValue(getCollateralBalance()).mul(100); uint256 debtAmt = getDebtBalance(); return collateralAmt.div(debtAmt); } // if borrow is true (for addCollateralAndBorrow): return (maxDebt - currentDebt) if positive value, otherwise return 0 // if borrow is false (for repayAndRedeemCollateral): return (currentDebt - maxDebt) if positive value, otherwise return 0 function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) { uint256 maxDebt = collateralAmt > 0 ? collateralValue(collateralAmt).mul(ratioBuffMax).div(_getBufferedMinRatio(ratioBuffMax)) : 0; uint256 debtAmt = getDebtBalance(); uint256 debt = 0; if (borrow && maxDebt >= debtAmt) { debt = maxDebt.sub(debtAmt); } else if (!borrow && debtAmt >= maxDebt) { debt = debtAmt.sub(maxDebt); } return (debt > 0) ? debt : 0; } function _getBufferedMinRatio(uint256 _multiplier) internal view returns (uint256) { require(ratioBuffMax > 0, "!ratioBufferMax"); require(minRatio > 0, "!minRatio"); return minRatio.mul(_multiplier).mul(ratioBuffMax.add(ratioBuff)).div(ratioBuffMax).div(100); } function borrowableDebt() public view returns (uint256) { uint256 collateralAmt = getCollateralBalance(); return calculateDebtFor(collateralAmt, true); } function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) { uint256 totalCollateral = getCollateralBalance(); uint256 collateralAmt = _redeemCollateralAmt >= totalCollateral ? 0 : totalCollateral.sub(_redeemCollateralAmt); return calculateDebtFor(collateralAmt, false); } // **** sub-strategy implementation **** function _depositUSDP(uint256 _usdpAmt) internal virtual; function _withdrawUSDP(uint256 _usdpAmt) internal virtual; // **** Oracle (using chainlink) **** function getLatestCollateralPrice() public view returns (uint256) { if (useUnitUsdOracle) { address unitOracleRegistry = IUnitCDPManager(cdpMgr01).oracleRegistry(); address unitUsdOracle = IUnitOracleRegistry(unitOracleRegistry).oracleByAsset(collateral); uint256 usdPriceInQ122 = IUnitUsdOracle(unitUsdOracle).assetToUsd(collateral, collateralDecimal); return uint256(usdPriceInQ122 / Q112).mul(collateralPriceDecimal).div(1e18); // usd price from unit protocol oracle in 1e18 decimal } require(unitOracle != address(0), "!_collateralOracle"); (, int256 price, , , ) = IChainlinkAggregator(unitOracle).latestRoundData(); if (price > 0) { if (collateralPriceEth) { (, int256 ethPrice, , , ) = IChainlinkAggregator(eth_usd).latestRoundData(); // eth price from chainlink in 1e8 decimal return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth ? 1e18 : 1); } else { return uint256(price).mul(collateralPriceDecimal).div(1e8); } } else { return 0; } } // **** Setters **** function setMinRatio(uint256 _minRatio) external { _onlyGovernance(); minRatio = _minRatio; } function setRatioBuff(uint256 _ratioBuff) external { _onlyGovernance(); ratioBuff = _ratioBuff; } function setDustMinDebt(uint256 _dustDebt) external { _onlyGovernance(); dustMinDebt = _dustDebt; } function setUseUnitUsdOracle(bool _useUnitUsdOracle) external { _onlyGovernance(); useUnitUsdOracle = _useUnitUsdOracle; } // **** Unit Protocol CDP actions **** function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _usdpAmt) internal { require(_usdpAmt.add(debtUsed()) < debtLimit(), "!exceedLimit"); _safeApproveHelper(collateral, unitVault, _collateralAmt); IUnitCDPManager(cdpMgr01).join(collateral, _collateralAmt, _usdpAmt); } function repayAndRedeemCollateral(uint256 _collateralAmt, uint256 _usdpAmt) internal { _safeApproveHelper(debtToken, unitVault, _usdpAmt); IUnitCDPManager(cdpMgr01).exit(collateral, _collateralAmt, _usdpAmt); } // **** State Mutation functions **** function keepMinRatio() external { _onlyCDPInUse(); _onlyAuthorizedActorsOrController(); uint256 requiredPaidback = requiredPaidDebt(0); if (requiredPaidback > 0) { _withdrawUSDP(requiredPaidback); uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this)); uint256 _actualPaidDebt = _currentDebtVal; uint256 _totalDebtWithoutFee = getDebtWithoutFee(); uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee); require(_actualPaidDebt > _fee, "!notEnoughForFee"); _actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first _actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee); require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment"); repayAndRedeemCollateral(0, _actualPaidDebt); } } /// @dev Internal deposit logic to be implemented by Strategies function _deposit(uint256 _want) internal override { if (_want > 0) { uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true); if (_newDebt > 0) { addCollateralAndBorrow(_want, _newDebt); uint256 wad = IERC20Upgradeable(debtToken).balanceOf(address(this)); _depositUSDP(_newDebt > wad ? wad : _newDebt); } } } // to avoid repay all debt resulting to close the CDP unexpectedly function _capMaxDebtPaid(uint256 _actualPaidDebt, uint256 _totalDebtWithoutFee) internal view returns (uint256) { uint256 _maxDebtToRepay = _totalDebtWithoutFee.sub(dustMinDebt); return _actualPaidDebt >= _maxDebtToRepay ? _maxDebtToRepay : _actualPaidDebt; } /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal override returns (uint256) { if (_amount == 0) { return _amount; } uint256 requiredPaidback = requiredPaidDebt(_amount); if (requiredPaidback > 0) { _withdrawUSDP(requiredPaidback); } bool _fullWithdraw = _amount >= balanceOfPool(); uint256 _wantBefore = IERC20Upgradeable(want).balanceOf(address(this)); if (!_fullWithdraw) { uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this)); uint256 _actualPaidDebt = _currentDebtVal; uint256 _totalDebtWithoutFee = getDebtWithoutFee(); uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee); require(_actualPaidDebt > _fee, "!notEnoughForFee"); _actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first _actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee); require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment"); repayAndRedeemCollateral(_amount, _actualPaidDebt); } else { require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= getDebtBalance(), "!notEnoughFullRepayment"); repayAndRedeemCollateral(_amount, getDebtBalance()); require(getDebtBalance() == 0, "!leftDebt"); require(getCollateralBalance() == 0, "!leftCollateral"); } uint256 _wantAfter = IERC20Upgradeable(want).balanceOf(address(this)); return _wantAfter.sub(_wantBefore); } /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal override { _withdrawSome(balanceOfPool()); } } interface IChainlinkAggregator { function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } interface IBaseRewardsPool { //balance function balanceOf(address _account) external view returns (uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external returns (bool); //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool); //claim rewards function getReward() external returns (bool); //stake a convex tokenized deposit function stake(uint256 _amount) external returns (bool); //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account, uint256 _amount) external returns (bool); function getReward(address _account, bool _claimExtras) external returns (bool); function rewards(address _account) external view returns (uint256); function earned(address _account) external view returns (uint256); function stakingToken() external view returns (address); } interface IBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function depositAll(uint256 _pid, bool _stake) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns (bool); function withdrawAll(uint256 _pid) external returns (bool); } interface ICvxMinter { function reductionPerCliff() external view returns (uint256); function totalCliffs() external view returns (uint256); function maxSupply() external view returns (uint256); } interface ICurveExchange { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy( int128, int128 j, uint256 dx ) external view returns (uint256); function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256 amount); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_one_coin( uint256 _token_amounts, int128 i, uint256 min_amount ) external; } interface ICurveFi { function get_virtual_price() external view returns (uint256 out); function add_liquidity( // renbtc/tbtc pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function get_dy( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function remove_liquidity( uint256 _amount, uint256 deadline, uint256[2] calldata min_amounts ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) 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 remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external; function commit_new_parameters( int128 amplification, int128 new_fee, int128 new_admin_fee ) external; function apply_new_parameters() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function coins(int128 arg0) external returns (address out); function underlying_coins(int128 arg0) external returns (address out); function balances(int128 arg0) external returns (uint256 out); function A() external returns (int128 out); function fee() external returns (int128 out); function admin_fee() external returns (int128 out); function owner() external returns (address out); function admin_actions_deadline() external returns (uint256 out); function transfer_ownership_deadline() external returns (uint256 out); function future_A() external returns (int128 out); function future_fee() external returns (int128 out); function future_admin_fee() external returns (int128 out); function future_owner() external returns (address out); function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out); } interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external view returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } interface ICurveMintr { function mint(address) external; function minted(address arg0, address arg1) external view returns (uint256); } contract StrategyUnitProtocolRenbtc is StrategyUnitProtocolMeta { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; // strategy specific address public constant renbtc_collateral = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; uint256 public constant renbtc_collateral_decimal = 1e8; address public constant renbtc_oracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; uint256 public constant renbtc_price_decimal = 1; bool public constant renbtc_price_eth = false; bool public harvestToRepay = false; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public constant weth_decimal = 1e18; address public constant usdp3crv = 0x7Eb40E450b9655f4B3cC4259BCC731c63ff55ae6; address public constant usdp = debtToken; address public constant curvePool = 0x42d7025938bEc20B69cBae5A77421082407f053A; uint256 public constant usdp_decimal = 1e18; // yield-farming in usdp-3crv pool & Convex Finance address public stakingPool = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; uint256 public stakingPoolId = 28; address public constant rewardTokenCRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant rewardTokenCVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public rewardPool = 0x24DfFd1949F888F91A0c8341Fc98a3F280a782a8; // slippage protection for one-sided ape in/out uint256 public slippageRepayment = 500; // max 5% uint256 public slippageProtectionIn = 50; // max 0.5% uint256 public slippageProtectionOut = 50; // max 0.5% uint256 public keepCRV; uint256 public keepCVX; event RenBTCStratHarvest( uint256 crvHarvested, uint256 cvxHarvested, uint256 usdpRepaid, uint256 wantProcessed, uint256 governancePerformanceFee, uint256 strategistPerformanceFee ); struct HarvestData { uint256 crvHarvested; uint256 cvxHarvested; uint256 usdpRepaid; uint256 wantProcessed; uint256 governancePerformanceFee; uint256 strategistPerformanceFee; } // // feeConfig: governance/strategist/withdrawal/keepCRV // function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[1] memory _wantConfig, uint256[4] memory _feeConfig ) public initializer { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); require(_wantConfig[0] == renbtc_collateral, "!want"); want = _wantConfig[0]; collateral = renbtc_collateral; collateralDecimal = renbtc_collateral_decimal; unitOracle = renbtc_oracle; collateralPriceDecimal = renbtc_price_decimal; collateralPriceEth = renbtc_price_eth; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; keepCRV = _feeConfig[3]; keepCVX = keepCRV; // avoid empty value after clones minRatio = 150; ratioBuff = 200; useUnitUsdOracle = true; dustMinDebt = 10000; slippageRepayment = 500; slippageProtectionIn = 50; slippageProtectionOut = 50; stakingPoolId = 28; } // **** Setters **** function setSlippageRepayment(uint256 _repaymentSlippage) public{ _onlyGovernance(); require(_repaymentSlippage < MAX_FEE && _repaymentSlippage > 0, "!_repaymentSlippage"); slippageRepayment = _repaymentSlippage; } function setStakingPoolId(uint256 _poolId) public{ _onlyGovernance(); stakingPoolId = _poolId; } function setStakingPool(address _pool) public{ _onlyGovernance(); stakingPool = _pool; } function setRewardPool(address _pool) public{ _onlyGovernance(); rewardPool = _pool; } function setSlippageProtectionIn(uint256 _slippage) external { _onlyGovernance(); require(_slippage < MAX_FEE && _slippage > 0, "!_slippageProtectionIn"); slippageProtectionIn = _slippage; } function setSlippageProtectionOut(uint256 _slippage) external { _onlyGovernance(); require(_slippage < MAX_FEE && _slippage > 0, "!_slippageProtectionOut"); slippageProtectionOut = _slippage; } function setKeepCRV(uint256 _keepCRV) external { _onlyGovernance(); keepCRV = _keepCRV; } function setKeepCVX(uint256 _keepCVX) external { _onlyGovernance(); keepCVX = _keepCVX; } function setHarvestToRepay(bool _repay) public{ _onlyGovernance(); harvestToRepay = _repay; } // **** State Mutation functions **** function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; (uint256 _crvRecycled, uint256 _cvxRecycled) = _collectStakingRewards(harvestData); // Convert CRV & CVX Rewards to WETH _convertRewards(); // Repay borrowed debt uint256 _wethAmount = IERC20Upgradeable(weth).balanceOf(address(this)); if (_wethAmount > 0){ harvestData.usdpRepaid = _repayDebt(_wethAmount); } // Convert WETH to Want for reinvestement _wethAmount = IERC20Upgradeable(weth).balanceOf(address(this)); if (_wethAmount > 0 && !harvestToRepay) { address[] memory path = new address[](2); path[0] = weth; path[1] = want; _swapExactTokensForTokens(uniswap, weth, _wethAmount, path); } // Take fees from want increase, and deposit remaining harvestData.wantProcessed = IERC20Upgradeable(want).balanceOf(address(this)); uint256 _wantDeposited; if (harvestData.wantProcessed > 0 && !harvestToRepay) { (harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee) = _processPerformanceFees(harvestData.wantProcessed); // Reinvest remaining want _wantDeposited = IERC20Upgradeable(want).balanceOf(address(this)); if (_wantDeposited > 0) { _deposit(_wantDeposited); } } emit RenBTCStratHarvest(harvestData.crvHarvested, harvestData.cvxHarvested, harvestData.usdpRepaid, harvestData.wantProcessed, harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee); emit Harvest(_wantDeposited, block.number); return harvestData; } function _collectStakingRewards(HarvestData memory harvestData) internal returns(uint256, uint256){ uint256 _before = IERC20Upgradeable(want).balanceOf(address(this)); uint256 _beforeCrv = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this)); uint256 _beforeCvx = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this)); // Harvest from Convex Finance IBaseRewardsPool(rewardPool).getReward(address(this), true); uint256 _afterCrv = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this)); uint256 _afterCvx = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this)); harvestData.crvHarvested = _afterCrv.sub(_beforeCrv); harvestData.cvxHarvested = _afterCvx.sub(_beforeCvx); uint256 _crv = _afterCrv; uint256 _cvx = _afterCvx; // Transfer CRV & CVX token to Rewards wallet as configured uint256 _keepCrv = _crv.mul(keepCRV).div(MAX_FEE); uint256 _keepCvx = _cvx.mul(keepCVX).div(MAX_FEE); IERC20Upgradeable(rewardTokenCRV).safeTransfer(IController(controller).rewards(), _keepCrv); IERC20Upgradeable(rewardTokenCVX).safeTransfer(IController(controller).rewards(), _keepCvx); uint256 _crvRecycled = _crv.sub(_keepCrv); uint256 _cvxRecycled = _cvx.sub(_keepCvx); return (_crvRecycled, _cvxRecycled); } function _repayDebt(uint256 _wethAmount) internal returns(uint256) { uint256 _repaidDebt; if (harvestToRepay){ // Repay debt ONLY to skip reinvest in case of strategy migration period _repaidDebt = _swapRewardsToDebt(_wethAmount); } else { // Repay debt first uint256 dueFee = getDueFee(); if (dueFee > 0){ uint256 _swapIn = calcETHSwappedForFeeRepayment(dueFee, _wethAmount); _repaidDebt = _swapRewardsToDebt(_swapIn); require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= dueFee, '!notEnoughRepaymentDuringHarvest'); uint256 debtTotalBefore = getDebtBalance(); repayAndRedeemCollateral(0, dueFee); require(getDebtBalance() < debtTotalBefore, '!repayDebtDuringHarvest'); } } return _repaidDebt; } function _convertRewards() internal { uint256 _rewardCRV = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this)); uint256 _rewardCVX = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this)); if (_rewardCRV > 0) { address[] memory _swapPath = new address[](2); _swapPath[0] = rewardTokenCRV; _swapPath[1] = weth; _swapExactTokensForTokens(sushiswap, rewardTokenCRV, _rewardCRV, _swapPath); } if (_rewardCVX > 0) { address[] memory _swapPath = new address[](2); _swapPath[0] = rewardTokenCVX; _swapPath[1] = weth; _swapExactTokensForTokens(sushiswap, rewardTokenCVX, _rewardCVX, _swapPath); } } function _swapRewardsToDebt(uint256 _swapIn) internal returns (uint256){ address[] memory _swapPath = new address[](2); _swapPath[0] = weth; _swapPath[1] = debtToken; uint256 _beforeDebt = IERC20Upgradeable(debtToken).balanceOf(address(this)); _swapExactTokensForTokens(sushiswap, weth, _swapIn, _swapPath); return IERC20Upgradeable(debtToken).balanceOf(address(this)).sub(_beforeDebt); } function calcETHSwappedForFeeRepayment(uint256 _dueFee, uint256 _toSwappedETHBal) public view returns (uint256){ (,int ethPrice,,,) = IChainlinkAggregator(eth_usd).latestRoundData();// eth price from chainlink in 1e8 decimal uint256 toSwapped = _dueFee.mul(weth_decimal).div(usdp_decimal).mul(1e8).div(uint256(ethPrice)); uint256 _swapIn = toSwapped.mul(MAX_FEE.add(slippageRepayment)).div(MAX_FEE); return _swapIn > _toSwappedETHBal ? _toSwappedETHBal : _swapIn; } function _processPerformanceFees(uint256 _amount) internal returns (uint256 governancePerformanceFee, uint256 strategistPerformanceFee) { governancePerformanceFee = _processFee(want, _amount, performanceFeeGovernance, IController(controller).rewards()); strategistPerformanceFee = _processFee(want, _amount, performanceFeeStrategist, strategist); } function estimateMinCrvLPFromDeposit(uint256 _usdpAmt) public view returns(uint256){ uint256 _expectedOut = estimateRequiredUsdp3crv(_usdpAmt); _expectedOut = _expectedOut.mul(MAX_FEE.sub(slippageProtectionIn)).div(MAX_FEE); return _expectedOut; } function _depositUSDP(uint256 _usdpAmt) internal override { uint256 _maxSlip = estimateMinCrvLPFromDeposit(_usdpAmt); if (_usdpAmt > 0 && checkSlip(_usdpAmt, _maxSlip)) { _safeApproveHelper(debtToken, curvePool, _usdpAmt); uint256[2] memory amounts = [_usdpAmt, 0]; ICurveFi(curvePool).add_liquidity(amounts, _maxSlip); } uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); if (_usdp3crv > 0) { _safeApproveHelper(usdp3crv, stakingPool, _usdp3crv); IBooster(stakingPool).depositAll(stakingPoolId, true); } } function _withdrawUSDP(uint256 _usdpAmt) internal override { uint256 _requiredUsdp3crv = estimateRequiredUsdp3crv(_usdpAmt); _requiredUsdp3crv = _requiredUsdp3crv.mul(MAX_FEE.add(slippageProtectionOut)).div(MAX_FEE); // try to remove bit more uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); uint256 _withdrawFromStaking = _usdp3crv < _requiredUsdp3crv ? _requiredUsdp3crv.sub(_usdp3crv) : 0; if (_withdrawFromStaking > 0) { uint256 maxInStaking = IBaseRewardsPool(rewardPool).balanceOf(address(this)); uint256 _toWithdraw = maxInStaking < _withdrawFromStaking ? maxInStaking : _withdrawFromStaking; IBaseRewardsPool(rewardPool).withdrawAndUnwrap(_toWithdraw, false); } _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this)); if (_usdp3crv > 0) { _requiredUsdp3crv = _requiredUsdp3crv > _usdp3crv ? _usdp3crv : _requiredUsdp3crv; uint256 maxSlippage = _requiredUsdp3crv.mul(MAX_FEE.sub(slippageProtectionOut)).div(MAX_FEE); _safeApproveHelper(usdp3crv, curvePool, _requiredUsdp3crv); ICurveFi(curvePool).remove_liquidity_one_coin(_requiredUsdp3crv, 0, maxSlippage); } } // **** Views **** function virtualPriceToWant() public view returns (uint256) { return ICurveFi(curvePool).get_virtual_price(); } function estimateRequiredUsdp3crv(uint256 _usdpAmt) public view returns (uint256) { return _usdpAmt.mul(1e18).div(virtualPriceToWant()); } function checkSlip(uint256 _usdpAmt, uint256 _maxSlip) public view returns (bool) { uint256[2] memory amounts = [_usdpAmt, 0]; return ICurveExchange(curvePool).calc_token_amount(amounts, true) >= _maxSlip; } function balanceOfCrvLPToken() public view returns (uint256){ uint256 lpAmt = IBaseRewardsPool(rewardPool).balanceOf(address(this)); return lpAmt.add(IERC20Upgradeable(usdp3crv).balanceOf(address(this))); } function usdpOfPool() public view returns (uint256){ uint256 lpAmt = balanceOfCrvLPToken(); return usdp3crvToUsdp(lpAmt); } function usdp3crvToUsdp(uint256 _usdp3crv) public view returns (uint256) { if (_usdp3crv == 0) { return 0; } return virtualPriceToWant().mul(_usdp3crv).div(1e18); } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal override { require(usdp3crv != _asset, "!usdp3crv"); require(debtToken != _asset, "!usdp"); require(renbtc_collateral != _asset, "!renbtc"); } function getProtectedTokens() public override view returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = renbtc_collateral; protectedTokens[1] = debtToken; protectedTokens[2] = usdp3crv; return protectedTokens; } /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external override pure returns (string memory) { return "StrategyUnitProtocolRenbtc"; } // only include CRV earned function getHarvestable() public view returns (uint256) { return IBaseRewardsPool(rewardPool).earned(address(this)); } // https://etherscan.io/address/0x4e3fbd56cd56c3e72c1403e103b45db9da5b9d2b#code#L1091 function mintableCVX(uint256 _amount) public view returns (uint256) { uint256 _toMint = 0; uint256 supply = IERC20Upgradeable(rewardTokenCVX).totalSupply(); uint256 cliff = supply.div(ICvxMinter(rewardTokenCVX).reductionPerCliff()); uint256 totalCliffs = ICvxMinter(rewardTokenCVX).totalCliffs(); if (cliff < totalCliffs){ uint256 reduction = totalCliffs.sub(cliff); _amount = _amount.mul(reduction).div(totalCliffs); uint256 amtTillMax = ICvxMinter(rewardTokenCVX).maxSupply().sub(supply); if (_amount > amtTillMax){ _amount = amtTillMax; } _toMint = _amount; } return _toMint; } function getHarvestableCVX() public view returns (uint256) { uint256 _crvEarned = getHarvestable(); return mintableCVX(_crvEarned); } }
Convert CRV & CVX Rewards to WETH Repay borrowed debt Reinvest remaining want
function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; (uint256 _crvRecycled, uint256 _cvxRecycled) = _collectStakingRewards(harvestData); _convertRewards(); uint256 _wethAmount = IERC20Upgradeable(weth).balanceOf(address(this)); if (_wethAmount > 0){ harvestData.usdpRepaid = _repayDebt(_wethAmount); } if (_wethAmount > 0 && !harvestToRepay) { address[] memory path = new address[](2); path[0] = weth; path[1] = want; _swapExactTokensForTokens(uniswap, weth, _wethAmount, path); } uint256 _wantDeposited; if (harvestData.wantProcessed > 0 && !harvestToRepay) { (harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee) = _processPerformanceFees(harvestData.wantProcessed); _wantDeposited = IERC20Upgradeable(want).balanceOf(address(this)); if (_wantDeposited > 0) { _deposit(_wantDeposited); } } emit RenBTCStratHarvest(harvestData.crvHarvested, harvestData.cvxHarvested, harvestData.usdpRepaid, harvestData.wantProcessed, harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee); emit Harvest(_wantDeposited, block.number); return harvestData; }
1,553,316
pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } 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 SealTokenSale is Pausable { using SafeMath for uint256; /** * @dev Supporter struct to allow tracking supporters KYC status and referrer address */ struct Supporter { bool hasKYC; address referrerAddress; } /** * @dev External Supporter struct to allow tracking reserved amounts by supporter */ struct ExternalSupporter { uint256 reservedAmount; } /** * @dev Token Sale States */ enum TokenSaleState {Private, Pre, Main, Finished} // Variables mapping(address => Supporter) public supportersMap; // Mapping with all the Token Sale participants (Private excluded) mapping(address => ExternalSupporter) public externalSupportersMap; // Mapping with external supporters SealToken public token; // ERC20 Token contract address address public vaultWallet; // Wallet address to which ETH and Company Reserve Tokens get forwarded address public airdropWallet; // Wallet address to which Unsold Tokens get forwarded address public kycWallet; // Wallet address for the KYC server uint256 public tokensSold; // How many tokens have been sold uint256 public tokensReserved; // How many tokens have been reserved uint256 public maxTxGasPrice; // Maximum transaction gas price allowed for fair-chance transactions TokenSaleState public currentState; // current Sale state uint256 public constant ONE_MILLION = 10 ** 6; // One million for token cap calculation reference uint256 public constant PRE_SALE_TOKEN_CAP = 384 * ONE_MILLION * 10 ** 18; // Maximum amount that can be sold during the Pre Sale period uint256 public constant TOKEN_SALE_CAP = 492 * ONE_MILLION * 10 ** 18; // Maximum amount of tokens that can be sold by this contract uint256 public constant TOTAL_TOKENS_SUPPLY = 1200 * ONE_MILLION * 10 ** 18; // Total supply that will be minted uint256 public constant MIN_ETHER = 0.1 ether; // Minimum ETH Contribution allowed during the crowd sale /* Minimum PreSale Contributions in Ether */ uint256 public constant PRE_SALE_MIN_ETHER = 1 ether; // Minimum to get 10% Bonus Tokens uint256 public constant PRE_SALE_15_BONUS_MIN = 60 ether; // Minimum to get 15% Bonus Tokens uint256 public constant PRE_SALE_20_BONUS_MIN = 300 ether; // Minimum to get 20% Bonus Tokens uint256 public constant PRE_SALE_30_BONUS_MIN = 1200 ether; // Minimum to get 30% Bonus Tokens /* Rate */ uint256 public tokenBaseRate; // Base rate uint256 public referrerBonusRate; // Referrer Bonus Rate with 2 decimals (250 for 2.5% bonus for example) uint256 public referredBonusRate; // Referred Bonus Rate with 2 decimals (250 for 2.5% bonus for example) /** * @dev Modifier to only allow Owner or KYC Wallet to execute a function */ modifier onlyOwnerOrKYCWallet() { require(msg.sender == owner || msg.sender == kycWallet); _; } /** * Event for token purchase logging * @param purchaser The wallet address that bought the tokens * @param value How many Weis were paid for the purchase * @param amount The amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for token reservation * @param wallet The beneficiary wallet address * @param amount The amount of tokens */ event TokenReservation(address indexed wallet, uint256 amount); /** * Event for token reservation confirmation * @param wallet The beneficiary wallet address * @param amount The amount of tokens */ event TokenReservationConfirmation(address indexed wallet, uint256 amount); /** * Event for token reservation cancellation * @param wallet The beneficiary wallet address * @param amount The amount of tokens */ event TokenReservationCancellation(address indexed wallet, uint256 amount); /** * Event for kyc status change logging * @param user User address * @param isApproved KYC approval state */ event KYC(address indexed user, bool isApproved); /** * Event for referrer set * @param user User address * @param referrerAddress Referrer address */ event ReferrerSet(address indexed user, address indexed referrerAddress); /** * Event for referral bonus incomplete * @param userAddress User address * @param missingAmount Missing Amount */ event ReferralBonusIncomplete(address indexed userAddress, uint256 missingAmount); /** * Event for referral bonus minted * @param userAddress User address * @param amount Amount minted */ event ReferralBonusMinted(address indexed userAddress, uint256 amount); /** * Constructor * @param _vaultWallet Vault address * @param _airdropWallet Airdrop wallet address * @param _kycWallet KYC address * @param _tokenBaseRate Token Base rate (Tokens/ETH) * @param _referrerBonusRate Referrer Bonus rate (2 decimals, ex 250 for 2.5%) * @param _referredBonusRate Referred Bonus rate (2 decimals, ex 250 for 2.5%) * @param _maxTxGasPrice Maximum gas price allowed when buying tokens */ function SealTokenSale( address _vaultWallet, address _airdropWallet, address _kycWallet, uint256 _tokenBaseRate, uint256 _referrerBonusRate, uint256 _referredBonusRate, uint256 _maxTxGasPrice ) public { require(_vaultWallet != address(0)); require(_airdropWallet != address(0)); require(_kycWallet != address(0)); require(_tokenBaseRate > 0); require(_referrerBonusRate > 0); require(_referredBonusRate > 0); require(_maxTxGasPrice > 0); vaultWallet = _vaultWallet; airdropWallet = _airdropWallet; kycWallet = _kycWallet; tokenBaseRate = _tokenBaseRate; referrerBonusRate = _referrerBonusRate; referredBonusRate = _referredBonusRate; maxTxGasPrice = _maxTxGasPrice; tokensSold = 0; tokensReserved = 0; token = new SealToken(); // init sale state; currentState = TokenSaleState.Private; } /* fallback function can be used to buy tokens */ function() public payable { buyTokens(); } /* low level token purchase function */ function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGasPrice); // make sure we're in pre or main sale period require(isPublicTokenSaleRunning()); // check if KYC ok require(userHasKYC(msg.sender)); // check user is sending enough Wei for the stage's rules require(aboveMinimumPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; // calculate token amount uint256 bonusMultiplier = getBonusMultiplier(weiAmountSent); uint256 newTokens = weiAmountSent.mul(tokenBaseRate).mul(bonusMultiplier).div(100); // check totals and mint the tokens checkTotalsAndMintTokens(sender, newTokens, false); // Log Event TokenPurchase(sender, weiAmountSent, newTokens); // forward the funds to the vault wallet vaultWallet.transfer(msg.value); } /** * @dev Reserve Tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function reserveTokens(address _wallet, uint256 _amount) public onlyOwner { // check amount positive require(_amount > 0); // check destination address not null require(_wallet != address(0)); // make sure that we're in private sale or presale require(isPrivateSaleRunning() || isPreSaleRunning()); // check cap uint256 totalTokensReserved = tokensReserved.add(_amount); require(tokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP); // update total reserved tokensReserved = totalTokensReserved; // save user reservation externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.add(_amount); // Log Event TokenReservation(_wallet, _amount); } /** * @dev Confirm Reserved Tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function confirmReservedTokens(address _wallet, uint256 _amount) public onlyOwner { // check amount positive require(_amount > 0); // check destination address not null require(_wallet != address(0)); // make sure the sale hasn't ended yet require(!hasEnded()); // check amount not more than reserved require(_amount <= externalSupportersMap[_wallet].reservedAmount); // check totals and mint the tokens checkTotalsAndMintTokens(_wallet, _amount, true); // Log Event TokenReservationConfirmation(_wallet, _amount); } /** * @dev Cancel Reserved Tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function cancelReservedTokens(address _wallet, uint256 _amount) public onlyOwner { // check amount positive require(_amount > 0); // check destination address not null require(_wallet != address(0)); // make sure the sale hasn't ended yet require(!hasEnded()); // check amount not more than reserved require(_amount <= externalSupportersMap[_wallet].reservedAmount); // update total reserved tokensReserved = tokensReserved.sub(_amount); // update user reservation externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount); // Log Event TokenReservationCancellation(_wallet, _amount); } /** * @dev Check totals and Mint tokens * @param _wallet Destination Address * @param _amount Amount of tokens */ function checkTotalsAndMintTokens(address _wallet, uint256 _amount, bool _fromReservation) private { // check that we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(_amount); uint256 totalTokensReserved = tokensReserved; if (_fromReservation) { totalTokensReserved = totalTokensReserved.sub(_amount); } if (isMainSaleRunning()) { require(totalTokensSold + totalTokensReserved <= TOKEN_SALE_CAP); } else { require(totalTokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP); } // update contract state tokensSold = totalTokensSold; if (_fromReservation) { externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount); tokensReserved = totalTokensReserved; } // mint the tokens token.mint(_wallet, _amount); address userReferrer = getUserReferrer(_wallet); if (userReferrer != address(0)) { // Mint Referrer bonus mintReferralShare(_amount, userReferrer, referrerBonusRate); // Mint Referred bonus mintReferralShare(_amount, _wallet, referredBonusRate); } } /** * @dev Mint Referral Share * @param _amount Amount of tokens * @param _userAddress User Address * @param _bonusRate Bonus rate (2 decimals) */ function mintReferralShare(uint256 _amount, address _userAddress, uint256 _bonusRate) private { // calculate max tokens available uint256 currentCap; if (isMainSaleRunning()) { currentCap = TOKEN_SALE_CAP; } else { currentCap = PRE_SALE_TOKEN_CAP; } uint256 maxTokensAvailable = currentCap - tokensSold - tokensReserved; // check if we have enough tokens uint256 fullShare = _amount.mul(_bonusRate).div(10000); if (fullShare <= maxTokensAvailable) { // mint the tokens token.mint(_userAddress, fullShare); // update state tokensSold = tokensSold.add(fullShare); // log event ReferralBonusMinted(_userAddress, fullShare); } else { // mint the available tokens token.mint(_userAddress, maxTokensAvailable); // update state tokensSold = tokensSold.add(maxTokensAvailable); // log events ReferralBonusMinted(_userAddress, maxTokensAvailable); ReferralBonusIncomplete(_userAddress, fullShare - maxTokensAvailable); } } /** * @dev Start Presale */ function startPreSale() public onlyOwner { // make sure we're in the private sale state require(currentState == TokenSaleState.Private); // move to presale currentState = TokenSaleState.Pre; } /** * @dev Go back to private sale */ function goBackToPrivateSale() public onlyOwner { // make sure we're in the pre sale require(currentState == TokenSaleState.Pre); // go back to private currentState = TokenSaleState.Private; } /** * @dev Start Main sale */ function startMainSale() public onlyOwner { // make sure we're in the presale state require(currentState == TokenSaleState.Pre); // move to main sale currentState = TokenSaleState.Main; } /** * @dev Go back to Presale */ function goBackToPreSale() public onlyOwner { // make sure we're in the main sale require(currentState == TokenSaleState.Main); // go back to presale currentState = TokenSaleState.Pre; } /** * @dev Ends the operation of the contract */ function finishContract() public onlyOwner { // make sure we're in the main sale require(currentState == TokenSaleState.Main); // make sure there are no pending reservations require(tokensReserved == 0); // mark sale as finished currentState = TokenSaleState.Finished; // send the unsold tokens to the airdrop wallet uint256 unsoldTokens = TOKEN_SALE_CAP.sub(tokensSold); token.mint(airdropWallet, unsoldTokens); // send the company reserve tokens to the vault wallet uint256 notForSaleTokens = TOTAL_TOKENS_SUPPLY.sub(TOKEN_SALE_CAP); token.mint(vaultWallet, notForSaleTokens); // finish the minting of the token, so that transfers are allowed token.finishMinting(); // transfer ownership of the token contract to the owner, // so it isn't locked to be a child of the crowd sale contract token.transferOwnership(owner); } /** * @dev Updates the maximum allowed gas price that can be used when calling buyTokens() * @param _newMaxTxGasPrice The new maximum gas price */ function updateMaxTxGasPrice(uint256 _newMaxTxGasPrice) public onlyOwner { require(_newMaxTxGasPrice > 0); maxTxGasPrice = _newMaxTxGasPrice; } /** * @dev Updates the token baserate * @param _tokenBaseRate The new token baserate in tokens/eth */ function updateTokenBaseRate(uint256 _tokenBaseRate) public onlyOwner { require(_tokenBaseRate > 0); tokenBaseRate = _tokenBaseRate; } /** * @dev Updates the Vault Wallet address * @param _vaultWallet The new vault wallet */ function updateVaultWallet(address _vaultWallet) public onlyOwner { require(_vaultWallet != address(0)); vaultWallet = _vaultWallet; } /** * @dev Updates the KYC Wallet address * @param _kycWallet The new kyc wallet */ function updateKYCWallet(address _kycWallet) public onlyOwner { require(_kycWallet != address(0)); kycWallet = _kycWallet; } /** * @dev Approve user's KYC * @param _user User Address */ function approveUserKYC(address _user) onlyOwnerOrKYCWallet public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; KYC(_user, true); } /** * @dev Disapprove user's KYC * @param _user User Address */ function disapproveUserKYC(address _user) onlyOwnerOrKYCWallet public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = false; KYC(_user, false); } /** * @dev Approve user's KYC and sets referrer * @param _user User Address * @param _referrerAddress Referrer Address */ function approveUserKYCAndSetReferrer(address _user, address _referrerAddress) onlyOwnerOrKYCWallet public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; sup.referrerAddress = _referrerAddress; // log events KYC(_user, true); ReferrerSet(_user, _referrerAddress); } /** * @dev check if private sale is running */ function isPrivateSaleRunning() public view returns (bool) { return (currentState == TokenSaleState.Private); } /** * @dev check if pre sale or main sale are running */ function isPublicTokenSaleRunning() public view returns (bool) { return (isPreSaleRunning() || isMainSaleRunning()); } /** * @dev check if pre sale is running */ function isPreSaleRunning() public view returns (bool) { return (currentState == TokenSaleState.Pre); } /** * @dev check if main sale is running */ function isMainSaleRunning() public view returns (bool) { return (currentState == TokenSaleState.Main); } /** * @dev check if sale has ended */ function hasEnded() public view returns (bool) { return (currentState == TokenSaleState.Finished); } /** * @dev Check if user has passed KYC * @param _user User Address */ function userHasKYC(address _user) public view returns (bool) { return supportersMap[_user].hasKYC; } /** * @dev Get User's referrer address * @param _user User Address */ function getUserReferrer(address _user) public view returns (address) { return supportersMap[_user].referrerAddress; } /** * @dev Get User's reserved amount * @param _user User Address */ function getReservedAmount(address _user) public view returns (uint256) { return externalSupportersMap[_user].reservedAmount; } /** * @dev Returns the bonus multiplier to calculate the purchase rate * @param _weiAmount Purchase amount */ function getBonusMultiplier(uint256 _weiAmount) internal view returns (uint256) { if (isMainSaleRunning()) { return 100; } else if (isPreSaleRunning()) { if (_weiAmount >= PRE_SALE_30_BONUS_MIN) { // 30% bonus return 130; } else if (_weiAmount >= PRE_SALE_20_BONUS_MIN) { // 20% bonus return 120; } else if (_weiAmount >= PRE_SALE_15_BONUS_MIN) { // 15% bonus return 115; } else if (_weiAmount >= PRE_SALE_MIN_ETHER) { // 10% bonus return 110; } else { // Safeguard but this should never happen as aboveMinimumPurchase checks the minimum revert(); } } } /** * @dev Check if the user is buying above the required minimum */ function aboveMinimumPurchase() internal view returns (bool) { if (isMainSaleRunning()) { return msg.value >= MIN_ETHER; } else if (isPreSaleRunning()) { return msg.value >= PRE_SALE_MIN_ETHER; } else { return false; } } } 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 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]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract 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; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; 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) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract SealToken is MintableToken { // Constants string public constant name = "SealToken"; string public constant symbol = "SEAL"; uint8 public constant decimals = 18; /** * @dev Modifier to only allow transfers after the minting has been done */ modifier onlyWhenTransferEnabled() { require(mintingFinished); _; } modifier validDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); _; } function SealToken() public { } function transferFrom(address _from, address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public onlyWhenTransferEnabled returns (bool) { return super.approve(_spender, _value); } function increaseApproval (address _spender, uint _addedValue) public onlyWhenTransferEnabled returns (bool) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval (address _spender, uint _subtractedValue) public onlyWhenTransferEnabled returns (bool) { return super.decreaseApproval(_spender, _subtractedValue); } function transfer(address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) { return super.transfer(_to, _value); } }
low level token purchase function / Do not allow if gasprice is bigger than the maximum This is for fair-chance for all contributors, so no one can set a too-high transaction price and be able to buy earlier make sure we're in pre or main sale period check if KYC ok check user is sending enough Wei for the stage's rules calculate token amount check totals and mint the tokens Log Event forward the funds to the vault wallet
function buyTokens() public payable whenNotPaused { require(tx.gasprice <= maxTxGasPrice); require(isPublicTokenSaleRunning()); require(userHasKYC(msg.sender)); require(aboveMinimumPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; uint256 bonusMultiplier = getBonusMultiplier(weiAmountSent); uint256 newTokens = weiAmountSent.mul(tokenBaseRate).mul(bonusMultiplier).div(100); checkTotalsAndMintTokens(sender, newTokens, false); TokenPurchase(sender, weiAmountSent, newTokens); vaultWallet.transfer(msg.value); }
5,841,234
pragma solidity 0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ 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 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract StandardToken is ERC20 { using SafeMath for uint256; uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } modifier onlySufficientBalance(address from, uint256 value) { require(value <= _balanceOf[from], "Insufficient balance"); _; } modifier onlySufficientAllowance(address owner, address spender, uint256 value) { require(value <= _allowance[owner][spender], "Insufficient allowance"); _; } /** * @dev Transfers token to the specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public onlyValidAddress(to) onlySufficientBalance(msg.sender, value) returns (bool) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Transfers 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 onlyValidAddress(to) onlySufficientBalance(from, value) onlySufficientAllowance(from, msg.sender, value) returns (bool) { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } /** * @dev Approves 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 onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @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 onlyValidAddress(spender) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Decreases the amount of tokens that an owner allowed to a spender. * * approve should be called when _allowance[spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @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 onlyValidAddress(spender) onlySufficientAllowance(msg.sender, spender, subtractedValue) returns (bool) { _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } /** * @dev Gets 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 _balanceOf[owner]; } /** * @dev Checks 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 _allowance[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". * @dev Based on https://github.com/OpenZeppelin/zeppelin-soliditysettable */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Can only be called by the owner"); _; } modifier onlyValidAddress(address addr) { require(addr != address(0), "Address cannot be zero"); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @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 onlyValidAddress(newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Standard token with minting * @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity */ contract MintableToken is StandardToken, Ownable { uint256 public cap; modifier onlyNotExceedingCap(uint256 amount) { require(_totalSupply.add(amount) <= cap, "Total supply must not exceed cap"); _; } constructor(uint256 _cap) public { cap = _cap; } /** * @dev Creates new tokens for the given address * @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 onlyOwner onlyValidAddress(to) onlyNotExceedingCap(amount) returns (bool) { _mint(to, amount); return true; } /** * @dev Creates new tokens for the given addresses * @param addresses The array of addresses that will receive the minted tokens. * @param amounts The array of amounts of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintMany(address[] addresses, uint256[] amounts) public onlyOwner onlyNotExceedingCap(_sum(amounts)) returns (bool) { require( addresses.length == amounts.length, "Addresses array must be the same size as amounts array" ); for (uint256 i = 0; i < addresses.length; i++) { _mint(addresses[i], amounts[i]); } return true; } function _mint(address to, uint256 amount) internal onlyValidAddress(to) { _totalSupply = _totalSupply.add(amount); _balanceOf[to] = _balanceOf[to].add(amount); emit Transfer(address(0), to, amount); } function _sum(uint256[] arr) internal pure returns (uint256) { uint256 aggr = 0; for (uint256 i = 0; i < arr.length; i++) { aggr = aggr.add(arr[i]); } return aggr; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { /** * @dev Burns a specific amount of tokens. * @param amount The amount of token to be burned. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from The account whose tokens will be burnt. * @param amount The amount of token that will be burnt. */ function burnFrom(address from, uint256 amount) public onlyValidAddress(from) onlySufficientAllowance(from, msg.sender, amount) { _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(amount); _burn(from, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param from The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address from, uint256 amount) internal onlySufficientBalance(from, amount) { _totalSupply = _totalSupply.sub(amount); _balanceOf[from] = _balanceOf[from].sub(amount); emit Transfer(from, address(0), amount); } } contract TradeTokenX is MintableToken, BurnableToken { string public name = "Trade Token X"; string public symbol = "TIOx"; uint8 public decimals = 18; uint256 public cap = 223534822661022743815939072; // solhint-disable-next-line no-empty-blocks constructor() public MintableToken(cap) {} }
Internal function that burns an amount of the token of a given account. from The account whose tokens will be burnt. amount The amount that will be burnt./
function _burn(address from, uint256 amount) internal onlySufficientBalance(from, amount) { _totalSupply = _totalSupply.sub(amount); _balanceOf[from] = _balanceOf[from].sub(amount); emit Transfer(from, address(0), amount); }
12,735,904
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ 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--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there&#39;s a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there&#39;s a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;s do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity&#39;s ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;t access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> pragma solidity ^0.4.19; /// @title EtherHiLo /// @dev the contract than handles the EtherHiLo app contract EtherHiLo is usingOraclize, Ownable { uint8 constant NUM_DICE_SIDES = 13; // settings uint public rngCallbackGas; uint public minBet; uint public maxBetThresholdPct; bool public gameRunning; // state uint public balanceInPlay; uint public totalGamesPlayed; uint public totalBetsMade; uint public totalWinnings; mapping(address => Game) private gamesInProgress; mapping(uint => address) private rollIdToGameAddress; mapping(uint => uint) private failedRolls; event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet); event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll); event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction); event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout); event GameError(address indexed player, uint indexed playerGameNumber, uint rollId); enum BetDirection { None, Low, High } // the game object struct Game { address player; BetDirection direction; uint id; uint bet; uint firstRoll; uint when; } // modifier that requires the game is running modifier gameIsRunning() { require(gameRunning); _; } // modifier that requires there is a game in progress // for the player modifier gameInProgress(address player) { require(player != address(0)); require(gamesInProgress[player].player != address(0)); _; } // modifier that requires there is not a game in progress // for the player modifier gameNotInProgress(address player) { require(player != address(0)); require(gamesInProgress[player].player == address(0)); _; } // modifier that requires the caller come from oraclize modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } // the constructor function EtherHiLo() public { oraclize_setProof(proofType_Ledger); setRNGCallbackGas(1000000); setRNGCallbackGasPrice(4000000000 wei); setMinBet(1 finney); setGameRunning(true); setMaxBetThresholdPct(50); totalGamesPlayed = 0; totalBetsMade = 0; totalWinnings = 0; } /// Default function function() external payable { } /// ======================= /// EXTERNAL GAME RELATED FUNCTIONS // begins a game function beginGame() public payable gameIsRunning gameNotInProgress(msg.sender) { address player = msg.sender; uint bet = msg.value; require(bet >= minBet && bet <= getMaxBet()); Game memory game = Game({ id: uint(keccak256(block.number, block.timestamp, player, bet)), player: player, bet: bet, firstRoll: 0, direction: BetDirection.None, when: block.timestamp }); balanceInPlay = balanceInPlay + game.bet; totalGamesPlayed = totalGamesPlayed + 1; totalBetsMade = totalBetsMade + game.bet; gamesInProgress[player] = game; if (rollDie(player, game.id)) { GameStarted(player, game.id, bet); } } // finishes a game that is in progress function finishGame(BetDirection direction) public gameInProgress(msg.sender) { address player = msg.sender; require(player != address(0)); require(direction != BetDirection.None); Game storage game = gamesInProgress[player]; require(game.player != address(0)); game.direction = direction; gamesInProgress[player] = game; if (rollDie(player, game.id)) { DirectionChosen(player, game.id, game.bet, game.firstRoll, direction); } } // determins whether or not the caller is in a game function getGameState(address player) public view returns (bool, uint, uint, BetDirection, uint, uint, uint) { return ( gamesInProgress[player].player != address(0), gamesInProgress[player].bet, gamesInProgress[player].firstRoll, gamesInProgress[player].direction, gamesInProgress[player].id, getMinBet(), getMaxBet() ); } // Returns the minimum bet function getMinBet() public view returns (uint) { return minBet; } // Returns the maximum bet function getMaxBet() public view returns (uint) { return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12); } // calculates winnings for the given bet and percent function calculateWinnings(uint bet, uint percent) public pure returns (uint) { return SafeMath.div(SafeMath.mul(bet, percent), 100); } // Returns the win percent when going low on the given number function getLowWinPercent(uint number) public pure returns (uint) { require(number >= 2 && number <= NUM_DICE_SIDES); if (number == 2) { return 1200; } else if (number == 3) { return 500; } else if (number == 4) { return 300; } else if (number == 5) { return 300; } else if (number == 6) { return 200; } else if (number == 7) { return 180; } else if (number == 8) { return 150; } else if (number == 9) { return 140; } else if (number == 10) { return 130; } else if (number == 11) { return 120; } else if (number == 12) { return 110; } else if (number == 13) { return 100; } } // Returns the win percent when going high on the given number function getHighWinPercent(uint number) public pure returns (uint) { require(number >= 1 && number < NUM_DICE_SIDES); if (number == 1) { return 100; } else if (number == 2) { return 110; } else if (number == 3) { return 120; } else if (number == 4) { return 130; } else if (number == 5) { return 140; } else if (number == 6) { return 150; } else if (number == 7) { return 180; } else if (number == 8) { return 200; } else if (number == 9) { return 300; } else if (number == 10) { return 300; } else if (number == 11) { return 500; } else if (number == 12) { return 1200; } } /// ======================= /// INTERNAL GAME RELATED FUNCTIONS // process a successful roll function processDiceRoll(address player, uint roll) private { Game storage game = gamesInProgress[player]; require(game.player != address(0)); if (game.firstRoll == 0) { game.firstRoll = roll; gamesInProgress[player] = game; FirstRoll(player, game.id, game.bet, game.firstRoll); return; } uint finalRoll = roll; uint winnings = 0; if (game.direction == BetDirection.High && finalRoll > game.firstRoll) { winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll)); } else if (game.direction == BetDirection.Low && finalRoll < game.firstRoll) { winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll)); } // this should never happen according to the odds, // and the fact that we don&#39;t allow people to bet // so large that they can take the whole pot in one // fell swoop - however, a number of people could // theoretically all win simultaneously and cause // this scenario. This will try to at a minimum // send them back what they bet and then since it // is recorded on the blockchain we can verify that // the winnings sent don&#39;t match what they should be // and we can manually send the rest to the player. uint transferAmount = winnings; if (transferAmount > this.balance) { if (game.bet < this.balance) { transferAmount = game.bet; } else { transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100); } } balanceInPlay = balanceInPlay - game.bet; if (transferAmount > 0) { game.player.transfer(transferAmount); } totalWinnings = totalWinnings + winnings; GameFinished(player, game.id, game.bet, game.firstRoll, finalRoll, winnings, transferAmount); delete gamesInProgress[player]; } // roll the dice for a player function rollDie(address player, uint gameId) private returns (bool) { uint N = 7; uint delay = 0; bytes32 _queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas); uint rollId = uint(keccak256(_queryId)); // avoid reorgs if (failedRolls[rollId] == rollId) { cleanupErrorGame(player, gameId, rollId); return false; } rollIdToGameAddress[rollId] = player; return true; } // called to cleanup an error in a game, usually caused by // a reorg or other weird blockchain anomoly. function cleanupErrorGame(address player, uint gameId, uint rollId) private { Game storage game = gamesInProgress[player]; if (gameId == 0) { gameId = game.id; } if (game.bet > 0) { game.player.transfer(game.bet); } delete gamesInProgress[player]; delete rollIdToGameAddress[rollId]; delete failedRolls[rollId]; GameError(player, gameId, rollId); } /// ======================= /// ORACLIZE RELATED FUNCTIONS // the callback function is called by Oraclize when the result is ready // the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: // the proof validity is fully verified on-chain function __callback(bytes32 _queryId, string _result, bytes _proof) public onlyOraclize { uint rollId = uint(keccak256(_queryId)); address player = rollIdToGameAddress[rollId]; // avoid reorgs if (player == address(0)) { failedRolls[rollId] = rollId; return; } if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) { cleanupErrorGame(player, 0, rollId); } else { uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1; processDiceRoll(player, randomNumber); } delete rollIdToGameAddress[rollId]; } /// OWNER / MANAGEMENT RELATED FUNCTIONS // fail safe for balance transfer function transferBalance(address to, uint amount) public onlyOwner { to.transfer(amount); } // cleans up a player abandoned game, but only if it&#39;s // greater than 24 hours old. function cleanupAbandonedGame(address player) public onlyOwner { require(player != address(0)); Game storage game = gamesInProgress[player]; require(game.player != address(0)); uint elapsed = block.timestamp - game.when; require(elapsed >= 86400); game.player.transfer(game.bet); delete gamesInProgress[game.player]; } // set RNG callback gas function setRNGCallbackGas(uint gas) public onlyOwner { rngCallbackGas = gas; } // set RNG callback gas function setRNGCallbackGasPrice(uint price) public onlyOwner { oraclize_setCustomGasPrice(price); } // set the minimum bet function setMinBet(uint bet) public onlyOwner { minBet = bet; } // set whether or not the game is running function setGameRunning(bool v) public onlyOwner { gameRunning = v; } // set the max bet threshold percent function setMaxBetThresholdPct(uint v) public onlyOwner { maxBetThresholdPct = v; } // Transfers the current balance to the owner and terminates the contract. function destroy() public onlyOwner { selfdestruct(owner); } // Transfers the current balance to the recepient and terminates the contract. function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } }
set RNG callback gas
function setRNGCallbackGas(uint gas) public onlyOwner { rngCallbackGas = gas; }
2,073,432
pragma solidity ^0.8.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; address private _firstOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } function firstOwner() public view returns (address) { return _firstOwner; } /** * @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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // 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 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; } // 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; } // 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); } // pragma solidity >=0.6.2; 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; } contract Apollo is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => bool) public preTrader; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _tLocked; mapping (address => uint256) private _balances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromMaxTx; mapping (address => bool) private _isExcludedFromMaxWallet; mapping (address => bool) private _isExcluded; mapping (address => uint256) private _purchaseHistory; address[] private _excluded; address payable _developerAddress; address payable _marketingAddress; uint256 private constant MAX = ~uint256(0); uint256 private _totalSupply = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _totalSupply)); uint256 private _tFeeTotal; uint256 private launchBlock = 0; string private _name = "Apollo"; string private _symbol = "APT"; uint8 private _decimals = 9; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; //LP will be turned on after day 0 to 1 uint256 public _liquidityFee = 0; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _developerFee = 3; //Hype Apes uint256 private _previousDeveloperFee = _developerFee; uint256 public _marketingFee = 7; //Apollo uint256 private _previousMarketingFee = _marketingFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool private tradingOpen; uint256 public _maxWallet = 15000000000000 * 10**9; //1.5% of TS uint256 public _maxTxAmount = 5000000000000 * 10**9; //0.5% of TS // set this number to adjust the rate of swaps uint256 public numTokensSellToAddToLiquidity = 250000 * 10**9; uint256 private _rateLimitSeconds = 5; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSend( uint256 tokensSwapped, uint256 ethReceived, uint256 tokens ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // KOVAN IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // MAINNET // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); // TESTNET // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // Add all the tokens created to the creator of the token _balances[msg.sender] = _totalSupply; // Emit an Transfer event to notify the blockchain that an Transfer has occured emit Transfer(address(0), msg.sender, _totalSupply); // Exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[address(0x000000000000000000000000000000000000dEaD)] = true; _isExcludedFromMaxTx[address(0)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); } function lockTimeOfWallet() public view returns (uint256) { return _tLocked[_msgSender()]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[_msgSender()] , "Wallet is still locked"); _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[sender] , "Wallet is still locked"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function lockWallet(uint256 time) public { _tLocked[_msgSender()] = block.timestamp + time; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } function setMaxTx(uint256 maxTx) external onlyOwner() { _maxTxAmount = maxTx * 10 ** 9; } function setMaxWallet(uint256 maxWallet) external onlyOwner() { _maxWallet = maxWallet * 10 ** 9; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function isExcludedFromMaxTx(address account) public view returns(bool) { return _isExcludedFromMaxTx[account]; } function excludeOrIncludeFromMaxTx(address account, bool exclude) public onlyOwner { _isExcludedFromMaxTx[account] = exclude; } function setDeveloperAddress(address payable developer) public onlyOwner { _developerAddress = developer; } function setMarketingAddress(address payable marketing) public onlyOwner { _marketingAddress = marketing; } function setMinTokensToSwap(uint256 _minTokens) external onlyOwner() { numTokensSellToAddToLiquidity = _minTokens * 10 ** 9; } function showDeveloperAddress() public view returns(address payable) { return _developerAddress; } function showMarketingaddress() public view returns(address payable) { return _marketingAddress; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setDeveloperFeePercent(uint256 developerFee) external onlyOwner { _developerFee = 0; if(developerFee <= 10) { _developerFee = developerFee; } } function setTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = 0; if(taxFee <= 10) { _taxFee = taxFee; } } function setMarketingFeePercent(uint256 marketingFee) external onlyOwner { _marketingFee = 0; if(marketingFee <= 10) { _marketingFee = marketingFee; } } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = 0; if(liquidityFee <= 10) { _liquidityFee = liquidityFee; } } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityPlusFees(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _totalSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_totalSupply)) return (_rTotal, _totalSupply); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityPlusFees(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee + _developerFee + _marketingFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _marketingFee == 0 && _developerFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousDeveloperFee = _developerFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _liquidityFee = 0; _developerFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _developerFee = _previousDeveloperFee; _marketingFee = _previousMarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { 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); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { //Trade start check if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } } if (_isExcludedFromMaxTx[from] == false && _isExcludedFromMaxTx[to] == false && _isExcludedFromMaxWallet[from] == false && _isExcludedFromMaxWallet[to] == false && to != uniswapV2Pair) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); checkBot(from,to); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 totalLiqFee = _marketingFee + _liquidityFee + _developerFee; // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> TART swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // Developer Portion uint256 developerBalance = newBalance.div(totalLiqFee).mul(_developerFee); uint256 developerPortion = otherHalf.div(totalLiqFee).mul(_developerFee); // Marketing Portion uint256 marketingBalance = newBalance.div(totalLiqFee).mul(_marketingFee); uint256 marketingPortion = otherHalf.div(totalLiqFee).mul(_marketingFee); uint256 finalBalance = newBalance.sub(developerBalance).sub(marketingBalance); uint256 finalHalf = otherHalf.sub(developerPortion).sub(marketingPortion); (bool sent, bytes memory data) = _developerAddress.call{value: developerBalance}(""); if(sent){ _tokenTransfer(address(this), 0x000000000000000000000000000000000000dEaD, developerPortion, false); emit Transfer(address(this), 0x000000000000000000000000000000000000dEaD, developerPortion); } else { addLiquidity(developerPortion, developerBalance, _developerAddress); } (sent, data) = _marketingAddress.call{value: marketingBalance}(""); if(sent){ _tokenTransfer(address(this), 0x000000000000000000000000000000000000dEaD, marketingPortion, false); emit Transfer(address(this), 0x000000000000000000000000000000000000dEaD, marketingPortion); } else { addLiquidity(marketingPortion, marketingBalance, _marketingAddress); } // add liquidity to uniswap addLiquidity(finalHalf, finalBalance, firstOwner()); // emit event for total liquidity added emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount, address lp) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable lp, block.timestamp ); } //pragma solidity ^0.8.4; /** * @notice _burn will destroy tokens from an address inputted and then decrease total supply * An Transfer event will emit with receiever set to zero address * * Requires * - Account cannot be zero * - Account balance has to be bigger or equal to amount */ function _burn(address account, uint256 amount) internal { require(account != address(0), "Apollo: cannot burn from zero address"); require(_balances[account] >= amount, "Apollo: Cannot burn more than the account owns"); // Remove the amount from the account balance _balances[account] = _balances[account] - amount; // Decrease totalSupply _totalSupply = _totalSupply - amount; // Emit event, use zero address as reciever emit Transfer(account, address(0), amount); } /** * @notice burn is used to destroy tokens on an address * * See {_burn} * Requires * - msg.sender must be the token owner * */ function burn(address account, uint256 amount) public onlyOwner returns(bool) { _burn(account, amount); return true; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function checkBot(address sender,address recipient) private { if (sender == address(uniswapV2Pair) && recipient != address(0) && recipient != address(uniswapV2Router) && recipient != owner()) { _purchaseHistory[recipient] = block.timestamp; } if(!_isExcludedFromFee[sender] && sender != address(0) && sender != address(uniswapV2Pair) && (recipient == address(uniswapV2Pair) || recipient == address(uniswapV2Router))) { require(_purchaseHistory[sender].add(_rateLimitSeconds) < block.timestamp, "Error: Are you a bot?"); } } //Allows Pretrading for Apollo function addPreTradingBatch(address[] memory newAddresses) external onlyOwner { uint length = newAddresses.length; for(uint x = 0; x < length;) { address account = newAddresses[x]; require(preTrader[account] != true, "TOKEN: Already enabled."); preTrader[account] = true; unchecked { ++x; } } } function removePreTradingBatch(address[] memory newAddresses) external onlyOwner { uint length = newAddresses.length; for(uint x = 0; x < length;) { address account = newAddresses[x]; require(preTrader[account] != false, "TOKEN: Already disabled."); preTrader[account] = false; unchecked { ++x; } } } //set trading for public function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } }
set trading for public
function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; }
2,303,442
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol
/ performs the bitcoin difficulty retarget implements the Bitcoin algorithm precisely _previousTarget the target of the previous period _firstTimestamp the timestamp of the first block in the difficulty period _secondTimestamp the timestamp of the last block in the difficulty period return the new period's target threshold Normalize ratio to factor of 4 if very long or very short
function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); }
4,857,097
./full_match/4/0xeA61Ea57fB850C04Ff90636fB3CB6c2e4f54108a/sources/contracts/modules/tokenswap/TokenSwapModule.sol
return uin32 The dealId of the new token swap/
function createSwap( address[] calldata _daos, address[] calldata _tokens, uint256[][] calldata _pathFrom, uint256[][] calldata _pathTo, address[] memory _daoplomats, uint256[][] memory _rewardPathTo, bytes32 _metadata, uint32 _deadline ) external returns (uint32) { for (uint256 i; i < _daos.length; ++i) { address dao = _daos[i]; if (!dealManager.hasDaoDepositManager(dao)) { dealManager.createDaoDepositManager(dao); } } return ( _createSwap( _daos, _tokens, _pathFrom, _pathTo, _daoplomats, _rewardPathTo, _metadata, _deadline ) ); }
12,301,718
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./OracleGetter.sol"; import "./ERC20.sol"; import "./Inflation.sol"; import "hardhat/console.sol"; /** @author Tellor Inc. @title Chorus @dev Chorus is a structure for issuing semi-stablecoins as community currencies **/ // slither-disable-next-line missing-inheritance contract Chorus is Inflation, OracleGetter, ERC20 { /*Events*/ event CollateralThreshold(uint256 _collateralThreshold);//emits if collateral threshold changes event CollateralPriceAge(uint256 _collateralPriceAge);//emits if collateral price age changes event Liquidate( address _party, uint256 _tokensAmnt, uint256 _collateralAmnt, uint256 _collateralPenalty );//emits upon a liquidation event LiquidationPenatly(uint256 _newPenalty);//emits when the liquidation penalty changes event MintTokens( address _holder, uint256 _amount, address _to, uint256 _collateralRatio );//emits when new tokens are minted event NewAdmin(address _newAdmin);//emits when a new admin is set event WithdrawCollateral( address _holder, uint256 _collateralAmnt, uint256 _collateralRatio );//emits when collateral is withdrawn event WithdrawToken(address _holder, uint256 _tokenAmnt, uint256 _collateralAmnt);//emits when tokens are withdrawn event WithdrawTokenRequest(address _user, uint256 _amount); /*Variables*/ struct WithdrawDetails{ uint256 amount; uint256 requestDate; } ERC20 public collateralToken; address public admin = msg.sender; uint256 private tknPrice = 1e18; uint256 public collateralID; // The collateral id used to check the Tellor oracle for its USD price. uint256 public collateralPriceGranularity; //usually 1000000 in the Tellor system uint256 public collateralThreshold = 15e17; // 150%. uint256 public collateralPriceAge = 3600; // e.g. 1hr. This is the delay in the feed from Tellor uint256 public liquidationPenatly = 0; uint256 public inflRatePerSec;// The rate at which the token decreases value. 1e18 precision. 100e18 is 100%. uint256 public inflLastUpdate = block.timestamp; address public inflBeneficiary; // Where to send the inflation tokens. mapping(address => WithdrawDetails) withdrawRequested; /*Modifiers*/ modifier onlyAdmin { require(msg.sender == admin, "not an admin"); _; } modifier within100e18Range(uint256 _value) { require(_value > 0 && _value < 100e18, "value not within allowed limits"); _; } /*Functions*/ /** * @dev This is the constructor, sets the inital paramaters in the system * The parameters include, the Tellor Address, collateral token's address, * collateral token's requestID, the price granualrity, the token name, * token's symbol, inflation rate per year, and the inflation beneficiary */ constructor( address payable _tellorAddress, address _collateralToken, uint256 _collateralID, uint256 _collateralPriceGranularity, string memory _tokenName, string memory _tokenSymbol, uint256 _inflRatePerYear, address _inflBeneficiary, bool _isWhitelisted ) OracleGetter(_tellorAddress) ERC20(_tokenName, _tokenSymbol,_isWhitelisted) within100e18Range(_inflRatePerYear) { collateralID = _collateralID; collateralToken = ERC20(_collateralToken); collateralPriceGranularity = _collateralPriceGranularity; require(_collateralPriceGranularity > 0 && _collateralPriceGranularity <= 1e18, "value not within allowed limits"); require(_inflBeneficiary != address(0), "benificiary address not set"); inflBeneficiary = _inflBeneficiary; inflRatePerSec = yearlyRateToPerSec(_inflRatePerYear); } /** * @dev Returns the current token price in USD reduced by the current inflation. * @return uint256 token price */ function collateralBalance() external view returns (uint256) { return collateralToken.balanceOf(address(this)); } /** * @dev Checks the Tellor oracle and gets the collateral price * @return uint256 collateral price in USD upscaled to e18 precision. */ // slither-disable-next-line timestamp function collateralPrice() public view returns (uint256) { (bool _didGet, uint256 _collateralPrice, ) = _getDataBefore(collateralID, block.timestamp - collateralPriceAge); require(_didGet, "getting oracle price"); return mul(_collateralPrice, div(1e18, collateralPriceGranularity)); } /** * @dev A view funciton to look at the collateralization of the system * @return uint256 collateral token balance of this address / totalSupply */ function collateralRatio() public view returns (uint256) { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); // slither-disable-next-line incorrect-equality if(totalSupply() == 0 || _collateralBalance == 0) { return 0; } uint256 _collateralValue = wmul(collateralPrice(), _collateralBalance); uint256 tokenSupplyWithInflInterest = accrueInterest(totalSupply(), inflRatePerSec, block.timestamp - inflLastUpdate); uint256 _tokenValue = wmul(tokenPrice(), tokenSupplyWithInflInterest); if(_tokenValue == 0){ return 100e18; } return wdiv(_collateralValue,_tokenValue); } /** * @dev Allows the admin to deposit collateral * @param _amount the amount of collateral token to deposit */ function depositCollateral(uint256 _amount) external onlyAdmin { require(_amount > 0, "deposit amount 0"); require( collateralToken.transferFrom(msg.sender, address(this), _amount), "failed collateral deposit transfer" ); } /** * @dev Function to allow anyone to liquidate the system if it is undercollateralized */ function liquidate() external { require( collateralRatio() < collateralThreshold, "collateral utilizatoin is above threshold" ); require(balanceOf(msg.sender) > 0, "msg sender doesn't own any tokens"); uint256 _tknSuplyRatio = wdiv(collateralToken.balanceOf(address(this)), totalSupply()); uint256 _tokensToBurn = balanceOf(msg.sender); uint256 _collatAmt = wmul(_tokensToBurn, _tknSuplyRatio); uint256 _collatPenalty = wmul(_collatAmt, liquidationPenatly); emit Liquidate(msg.sender, _tokensToBurn, _collatAmt, _collatPenalty); _burn(msg.sender, _tokensToBurn); require( collateralToken.transfer(msg.sender, sub(_collatAmt, _collatPenalty)), "collateral liquidation transfer fails" ); require( collateralToken.transfer(inflBeneficiary, _collatPenalty), "collateral liquidation penalty transfer fails" ); } /** * @dev Allows the admin to mint tokens up to the collateral threshold * @param _amount the amount of collateral tokens to mint * @param _to the address to mint them to; */ function mintToken(uint256 _amount, address _to) external onlyAdmin { _mint(_to, _amount); uint256 _cRatio = collateralRatio(); require( _cRatio >= collateralThreshold, "collateral utilization below the threshold" ); emit MintTokens(msg.sender, _amount, _to, _cRatio); } /** * @dev Allows a user to request to withdraw tokens * @param _amount the amount of tokens to withdraw */ function requestWithdrawToken(uint256 _amount) external { require(_amount > 0, "amount should be greater than 0"); require(balanceOf(msg.sender) >= _amount, "not enough balance"); withdrawRequested[msg.sender].requestDate = block.timestamp; withdrawRequested[msg.sender].amount = _amount; _transfer(msg.sender, address(this), _amount); emit WithdrawTokenRequest(msg.sender, _amount); } /** * @dev Allows the user to set a new admin address * @param _newAdmin the address of the new admin address */ function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0), "cannot send to the zero address"); admin = _newAdmin; emit NewAdmin(_newAdmin); } /** * @dev Allows the admin to set the collateral price Age (delay in feed from Tellor) * @param _amount the amount of delay in the price feed (we want to wait for disputes) */ function setCollateralPriceAge(uint256 _amount) external onlyAdmin { collateralPriceAge = _amount; emit CollateralPriceAge(_amount); } /** * @dev Allows the admin to set the Collateral threshold * @param _amount new collateral threshold */ function setCollateralThreshold(uint256 _amount) external onlyAdmin within100e18Range(_amount) { collateralThreshold = _amount; emit CollateralThreshold(_amount); } /** * @dev Allows the admin to set the liquidation penalty * @param _amount the amount of the liquidation penalty */ function setLiquidationPenatly(uint256 _amount) external onlyAdmin within100e18Range(_amount) { liquidationPenatly = wdiv(_amount, 100e18); // Convert to a fraction. emit LiquidationPenatly(liquidationPenatly); } /** * @dev Returns the current token price in USD reduced by the current inflation. * @return uint256 token price */ function tokenPrice() public view returns (uint256) { return accrueInflation( tknPrice, inflRatePerSec, block.timestamp - inflLastUpdate ); } /** * @dev Function to reduce token price by the inflation rate, * increases the total supply by the inflation rate and * sends the new tokens to the inflation beneficiary. */ // slither-disable-next-line timestamp function updateInflation() external { uint256 secsPassed = block.timestamp - inflLastUpdate; require(secsPassed > 0, "no inflation increase yet"); inflLastUpdate = block.timestamp; tknPrice = accrueInflation(tknPrice, inflRatePerSec, secsPassed); uint256 _tokensToMint = sub( accrueInterest(totalSupply(), inflRatePerSec, secsPassed), totalSupply() ); _mint(inflBeneficiary, _tokensToMint); } /** * @dev Allows the admin to withdraw collateral above the threshold * @param _amount the amount of collateral token to deposit */ function withdrawCollateral(uint256 _amount) external onlyAdmin { require( collateralToken.transfer(msg.sender, _amount), "collateral transfer fails" ); uint256 _cRatio = collateralRatio(); require( _cRatio >= collateralThreshold, "collateral utilization below the threshold" ); // slither-disable-next-line reentrancy-events emit WithdrawCollateral(msg.sender, _amount, _cRatio); } /** * @dev Allows a user to withdraw tokens */ function withdrawToken() external { WithdrawDetails memory wd = withdrawRequested[msg.sender]; uint256 _amount = withdrawRequested[msg.sender].amount; require(_amount > 0, "amount should be greater than 0"); uint256 _waitPeriod = 1 + 100 * _amount / totalSupply() / 5; //increases by 1 day for every 5 percent // slither-disable-next-line timestamp require(block.timestamp - wd.requestDate >= 86400 * _waitPeriod, "must wait to withdraw"); withdrawRequested[msg.sender].amount = 0; uint256 _collatPrice = collateralPrice(); uint256 _priceRatio = wdiv(tokenPrice(), _collatPrice); uint256 _collateralAmnt = wmul(_priceRatio, _amount); _burn(address(this), _amount); require( collateralToken.transfer(msg.sender, _collateralAmnt), "collateral transfer fail" ); // slither-disable-next-line reentrancy-events emit WithdrawToken(msg.sender, _amount, _collateralAmnt); } }
Allows the admin to deposit collateral _amount the amount of collateral token to deposit/
function depositCollateral(uint256 _amount) external onlyAdmin { require(_amount > 0, "deposit amount 0"); require( collateralToken.transferFrom(msg.sender, address(this), _amount), "failed collateral deposit transfer" ); }
6,418,379
// SPDX-License-Identifier: AGPL-3.0-only /* AdminEscrow.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Escrow.sol"; contract AdminEscrow is Escrow { address public constant ADMIN = address(0x4165CCb2ab09AC00Bb40C66FB296baCa183F899f); modifier onlyBeneficiary() override { require(_msgSender() == _beneficiary || _msgSender() == ADMIN, "Message sender is not a plan beneficiary"); _; } modifier onlyActiveBeneficiaryOrVestingManager() override { Allocator allocator = Allocator(contractManager.getContract("Allocator")); if (allocator.isVestingActive(_beneficiary)) { require(_msgSender() == _beneficiary || _msgSender() == ADMIN, "Message sender is not beneficiary"); } else { require( allocator.hasRole(allocator.VESTING_MANAGER_ROLE(), _msgSender()), "Message sender is not authorized" ); } _; } } // SPDX-License-Identifier: AGPL-3.0-only /* Escrow.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/delegation/IDelegationController.sol"; import "./interfaces/delegation/IDistributor.sol"; import "./interfaces/delegation/ITokenState.sol"; import "./Allocator.sol"; import "./Permissions.sol"; /** * @title Escrow * @dev This contract manages funds locked by the Allocator contract. */ contract Escrow is IERC777Recipient, IERC777Sender, Permissions { address internal _beneficiary; uint256 private _availableAmountAfterTermination; IERC1820Registry private _erc1820; modifier onlyBeneficiary() virtual { require(_msgSender() == _beneficiary, "Message sender is not a plan beneficiary"); _; } modifier onlyVestingManager() { Allocator allocator = Allocator(contractManager.getContract("Allocator")); require( allocator.hasRole(allocator.VESTING_MANAGER_ROLE(), _msgSender()), "Message sender is not a vesting manager" ); _; } modifier onlyActiveBeneficiaryOrVestingManager() virtual { Allocator allocator = Allocator(contractManager.getContract("Allocator")); if (allocator.isVestingActive(_beneficiary)) { require(_msgSender() == _beneficiary, "Message sender is not beneficiary"); } else { require( allocator.hasRole(allocator.VESTING_MANAGER_ROLE(), _msgSender()), "Message sender is not authorized" ); } _; } function initialize(address contractManagerAddress, address beneficiary) external initializer { require(beneficiary != address(0), "Beneficiary address is not set"); Permissions.initialize(contractManagerAddress); _beneficiary = beneficiary; _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } function tokensToSend( address, address, address to, uint256, bytes calldata, bytes calldata ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } /** * @dev Allows Beneficiary to retrieve vested tokens from the Escrow contract. * * IMPORTANT: Slashed tokens are non-transferable. */ function retrieve() external onlyBeneficiary { Allocator allocator = Allocator(contractManager.getContract("Allocator")); ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); uint256 vestedAmount = 0; if (allocator.isVestingActive(_beneficiary)) { vestedAmount = allocator.calculateVestedAmount(_beneficiary); } else { vestedAmount = _availableAmountAfterTermination; } uint256 escrowBalance = IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); uint256 locked = Math.max( allocator.getFullAmount(_beneficiary).sub(vestedAmount), tokenState.getAndUpdateForbiddenForDelegationAmount(address(this)) ); if (escrowBalance > locked) { require( IERC20(contractManager.getContract("SkaleToken")).transfer( _beneficiary, escrowBalance.sub(locked) ), "Error of token send" ); } } /** * @dev Allows Vesting Manager to retrieve remaining transferrable escrow balance * after beneficiary's termination. * * IMPORTANT: Slashed tokens are non-transferable. * * Requirements: * * - Allocator must be active. */ function retrieveAfterTermination(address destination) external onlyVestingManager { Allocator allocator = Allocator(contractManager.getContract("Allocator")); ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); require(destination != address(0), "Destination address is not set"); require(!allocator.isVestingActive(_beneficiary), "Vesting is active"); uint256 escrowBalance = IERC20(contractManager.getContract("SkaleToken")).balanceOf(address(this)); uint256 forbiddenToSend = tokenState.getAndUpdateLockedAmount(address(this)); if (escrowBalance > forbiddenToSend) { require( IERC20(contractManager.getContract("SkaleToken")).transfer( destination, escrowBalance.sub(forbiddenToSend) ), "Error of token send" ); } } /** * @dev Allows Beneficiary to propose a delegation to a validator. * * Requirements: * * - Beneficiary must be active. * - Beneficiary must have sufficient delegatable tokens. * - If trusted list is enabled, validator must be a member of the trusted * list. */ function delegate( uint256 validatorId, uint256 amount, uint256 delegationPeriod, string calldata info ) external onlyBeneficiary { Allocator allocator = Allocator(contractManager.getContract("Allocator")); require(allocator.isDelegationAllowed(_beneficiary), "Delegation is not allowed"); require(allocator.isVestingActive(_beneficiary), "Beneficiary is not Active"); IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.delegate(validatorId, amount, delegationPeriod, info); } /** * @dev Allows Beneficiary and Vesting manager to request undelegation. Only * Vesting manager can request undelegation after beneficiary is deactivated * (after beneficiary termination). * * Requirements: * * - Beneficiary and Vesting manager must be `msg.sender`. */ function requestUndelegation(uint256 delegationId) external onlyActiveBeneficiaryOrVestingManager { IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.requestUndelegation(delegationId); } /** * @dev Allows Beneficiary and Vesting manager to cancel a delegation proposal. Only * Vesting manager can request undelegation after beneficiary is deactivated * (after beneficiary termination). * * Requirements: * * - Beneficiary and Vesting manager must be `msg.sender`. */ function cancelPendingDelegation(uint delegationId) external onlyActiveBeneficiaryOrVestingManager { IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); delegationController.cancelPendingDelegation(delegationId); } /** * @dev Allows Beneficiary and Vesting manager to withdraw earned bounty. Only * Vesting manager can withdraw bounty to Allocator contract after beneficiary * is deactivated. * * IMPORTANT: Withdraws are only possible after 90 day initial network lock. * * Requirements: * * - Beneficiary or Vesting manager must be `msg.sender`. * - Beneficiary must be active when Beneficiary is `msg.sender`. */ function withdrawBounty(uint256 validatorId, address to) external onlyActiveBeneficiaryOrVestingManager { IDistributor distributor = IDistributor(contractManager.getContract("Distributor")); distributor.withdrawBounty(validatorId, to); } /** * @dev Allows Allocator contract to cancel vesting of a Beneficiary. Cancel * vesting is performed upon termination. */ function cancelVesting(uint256 vestedAmount) external allow("Allocator") { _availableAmountAfterTermination = vestedAmount; } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegationController.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Delegatable Token operations. */ interface IDelegationController { function delegate( uint256 validatorId, uint256 amount, uint256 delegationPeriod, string calldata info ) external; function requestUndelegation(uint256 delegationId) external; function cancelPendingDelegation(uint delegationId) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IDistributor.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Distributor contract. */ interface IDistributor { function withdrawBounty(uint256 validatorId, address to) external; } // SPDX-License-Identifier: AGPL-3.0-only /* ITokenState.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Token State contract. */ interface ITokenState { function getAndUpdateLockedAmount(address holder) external returns (uint); function getAndUpdateForbiddenForDelegationAmount(address holder) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* Allocator.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interfaces/openzeppelin/IProxyFactory.sol"; import "./interfaces/openzeppelin/IProxyAdmin.sol"; import "./interfaces/ITimeHelpers.sol"; import "./Escrow.sol"; import "./Permissions.sol"; /** * @title Allocator */ contract Allocator is Permissions, IERC777Recipient { uint256 constant private _SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant private _MONTHS_PER_YEAR = 12; enum TimeUnit { DAY, MONTH, YEAR } enum BeneficiaryStatus { UNKNOWN, CONFIRMED, ACTIVE, TERMINATED } struct Plan { uint256 totalVestingDuration; // months uint256 vestingCliff; // months TimeUnit vestingIntervalTimeUnit; uint256 vestingInterval; // amount of days/months/years bool isDelegationAllowed; bool isTerminatable; } struct Beneficiary { BeneficiaryStatus status; uint256 planId; uint256 startMonth; uint256 fullAmount; uint256 amountAfterLockup; } event PlanCreated( uint256 id ); IERC1820Registry private _erc1820; // array of Plan configs Plan[] private _plans; bytes32 public constant VESTING_MANAGER_ROLE = keccak256("VESTING_MANAGER_ROLE"); // beneficiary => beneficiary plan params mapping (address => Beneficiary) private _beneficiaries; // beneficiary => Escrow mapping (address => Escrow) private _beneficiaryToEscrow; modifier onlyVestingManager() { require( hasRole(VESTING_MANAGER_ROLE, _msgSender()), "Message sender is not a vesting manager" ); _; } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } /** * @dev Allows Vesting manager to activate a vesting and transfer locked * tokens from the Allocator contract to the associated Escrow address. * * Requirements: * * - Beneficiary address must be already confirmed. */ function startVesting(address beneficiary) external onlyVestingManager { require( _beneficiaries[beneficiary].status == BeneficiaryStatus.CONFIRMED, "Beneficiary has inappropriate status" ); _beneficiaries[beneficiary].status = BeneficiaryStatus.ACTIVE; require( IERC20(contractManager.getContract("SkaleToken")).transfer( address(_beneficiaryToEscrow[beneficiary]), _beneficiaries[beneficiary].fullAmount ), "Error of token sending" ); } /** * @dev Allows Vesting manager to define and add a Plan. * * Requirements: * * - Vesting cliff period must be less than or equal to the full period. * - Vesting step time unit must be in days, months, or years. * - Total vesting duration must equal vesting cliff plus entire vesting schedule. */ function addPlan( uint256 vestingCliff, // months uint256 totalVestingDuration, // months TimeUnit vestingIntervalTimeUnit, // 0 - day 1 - month 2 - year uint256 vestingInterval, // months or days or years bool canDelegate, // can beneficiary delegate all un-vested tokens bool isTerminatable ) external onlyVestingManager { require(totalVestingDuration > 0, "Vesting duration can't be zero"); require(vestingInterval > 0, "Vesting interval can't be zero"); require(totalVestingDuration >= vestingCliff, "Cliff period exceeds total vesting duration"); // can't check if vesting interval in days is correct because it depends on startMonth // This check is in connectBeneficiaryToPlan if (vestingIntervalTimeUnit == TimeUnit.MONTH) { uint256 vestingDurationAfterCliff = totalVestingDuration - vestingCliff; require( vestingDurationAfterCliff.mod(vestingInterval) == 0, "Vesting duration can't be divided into equal intervals" ); } else if (vestingIntervalTimeUnit == TimeUnit.YEAR) { uint256 vestingDurationAfterCliff = totalVestingDuration - vestingCliff; require( vestingDurationAfterCliff.mod(vestingInterval.mul(_MONTHS_PER_YEAR)) == 0, "Vesting duration can't be divided into equal intervals" ); } _plans.push(Plan({ totalVestingDuration: totalVestingDuration, vestingCliff: vestingCliff, vestingIntervalTimeUnit: vestingIntervalTimeUnit, vestingInterval: vestingInterval, isDelegationAllowed: canDelegate, isTerminatable: isTerminatable })); emit PlanCreated(_plans.length); } /** * @dev Allows Vesting manager to register a beneficiary to a Plan. * * Requirements: * * - Plan must already exist. * - The vesting amount must be less than or equal to the full allocation. * - The beneficiary address must not already be included in the any other Plan. */ function connectBeneficiaryToPlan( address beneficiary, uint256 planId, uint256 startMonth, uint256 fullAmount, uint256 lockupAmount ) external onlyVestingManager { require(_plans.length >= planId && planId > 0, "Plan does not exist"); require(fullAmount >= lockupAmount, "Incorrect amounts"); require(_beneficiaries[beneficiary].status == BeneficiaryStatus.UNKNOWN, "Beneficiary is already added"); if (_plans[planId - 1].vestingIntervalTimeUnit == TimeUnit.DAY) { uint256 vestingDurationInDays = _daysBetweenMonths( startMonth.add(_plans[planId - 1].vestingCliff), startMonth.add(_plans[planId - 1].totalVestingDuration) ); require( vestingDurationInDays.mod(_plans[planId - 1].vestingInterval) == 0, "Vesting duration can't be divided into equal intervals" ); } _beneficiaries[beneficiary] = Beneficiary({ status: BeneficiaryStatus.CONFIRMED, planId: planId, startMonth: startMonth, fullAmount: fullAmount, amountAfterLockup: lockupAmount }); _beneficiaryToEscrow[beneficiary] = _deployEscrow(beneficiary); } /** * @dev Allows Vesting manager to terminate vesting of a Escrow. Performed when * a beneficiary is terminated. * * Requirements: * * - Vesting must be active. */ function stopVesting(address beneficiary) external onlyVestingManager { require( _beneficiaries[beneficiary].status == BeneficiaryStatus.ACTIVE, "Cannot stop vesting for a non active beneficiary" ); require( _plans[_beneficiaries[beneficiary].planId - 1].isTerminatable, "Can't stop vesting for beneficiary with this plan" ); _beneficiaries[beneficiary].status = BeneficiaryStatus.TERMINATED; Escrow(_beneficiaryToEscrow[beneficiary]).cancelVesting(calculateVestedAmount(beneficiary)); } /** * @dev Returns vesting start month of the beneficiary's Plan. */ function getStartMonth(address beneficiary) external view returns (uint) { return _beneficiaries[beneficiary].startMonth; } /** * @dev Returns the final vesting date of the beneficiary's Plan. */ function getFinishVestingTime(address beneficiary) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[beneficiary]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; return timeHelpers.monthToTimestamp(beneficiaryPlan.startMonth.add(planParams.totalVestingDuration)); } /** * @dev Returns the vesting cliff period in months. */ function getVestingCliffInMonth(address beneficiary) external view returns (uint) { return _plans[_beneficiaries[beneficiary].planId - 1].vestingCliff; } /** * @dev Confirms whether the beneficiary is active in the Plan. */ function isVestingActive(address beneficiary) external view returns (bool) { return _beneficiaries[beneficiary].status == BeneficiaryStatus.ACTIVE; } /** * @dev Confirms whether the beneficiary is registered in a Plan. */ function isBeneficiaryRegistered(address beneficiary) external view returns (bool) { return _beneficiaries[beneficiary].status != BeneficiaryStatus.UNKNOWN; } /** * @dev Confirms whether the beneficiary's Plan allows all un-vested tokens to be * delegated. */ function isDelegationAllowed(address beneficiary) external view returns (bool) { return _plans[_beneficiaries[beneficiary].planId - 1].isDelegationAllowed; } /** * @dev Returns the locked and unlocked (full) amount of tokens allocated to * the beneficiary address in Plan. */ function getFullAmount(address beneficiary) external view returns (uint) { return _beneficiaries[beneficiary].fullAmount; } /** * @dev Returns the Escrow contract by beneficiary. */ function getEscrowAddress(address beneficiary) external view returns (address) { return address(_beneficiaryToEscrow[beneficiary]); } /** * @dev Returns the timestamp when vesting cliff ends and periodic vesting * begins. */ function getLockupPeriodEndTimestamp(address beneficiary) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[beneficiary]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; return timeHelpers.monthToTimestamp(beneficiaryPlan.startMonth.add(planParams.vestingCliff)); } /** * @dev Returns the time of the next vesting event. */ function getTimeOfNextVest(address beneficiary) external view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[beneficiary]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; uint256 firstVestingMonth = beneficiaryPlan.startMonth.add(planParams.vestingCliff); uint256 lockupEndTimestamp = timeHelpers.monthToTimestamp(firstVestingMonth); if (now < lockupEndTimestamp) { return lockupEndTimestamp; } require( now < timeHelpers.monthToTimestamp(beneficiaryPlan.startMonth.add(planParams.totalVestingDuration)), "Vesting is over" ); require(beneficiaryPlan.status != BeneficiaryStatus.TERMINATED, "Vesting was stopped"); uint256 currentMonth = timeHelpers.getCurrentMonth(); if (planParams.vestingIntervalTimeUnit == TimeUnit.DAY) { // TODO: it may be simplified if TimeHelpers contract in skale-manager is updated uint daysPassedBeforeCurrentMonth = _daysBetweenMonths(firstVestingMonth, currentMonth); uint256 currentMonthBeginningTimestamp = timeHelpers.monthToTimestamp(currentMonth); uint256 daysPassedInCurrentMonth = now.sub(currentMonthBeginningTimestamp).div(_SECONDS_PER_DAY); uint256 daysPassedBeforeNextVest = _calculateNextVestingStep( daysPassedBeforeCurrentMonth.add(daysPassedInCurrentMonth), planParams.vestingInterval ); return currentMonthBeginningTimestamp.add( daysPassedBeforeNextVest .sub(daysPassedBeforeCurrentMonth) .mul(_SECONDS_PER_DAY) ); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.MONTH) { return timeHelpers.monthToTimestamp( firstVestingMonth.add( _calculateNextVestingStep(currentMonth.sub(firstVestingMonth), planParams.vestingInterval) ) ); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.YEAR) { return timeHelpers.monthToTimestamp( firstVestingMonth.add( _calculateNextVestingStep( currentMonth.sub(firstVestingMonth), planParams.vestingInterval.mul(_MONTHS_PER_YEAR) ) ) ); } else { revert("Vesting interval timeunit is incorrect"); } } /** * @dev Returns the Plan parameters. * * Requirements: * * - Plan must already exist. */ function getPlan(uint256 planId) external view returns (Plan memory) { require(planId > 0 && planId <= _plans.length, "Plan Round does not exist"); return _plans[planId - 1]; } /** * @dev Returns the Plan parameters for a beneficiary address. * * Requirements: * * - Beneficiary address must be registered to an Plan. */ function getBeneficiaryPlanParams(address beneficiary) external view returns (Beneficiary memory) { require(_beneficiaries[beneficiary].status != BeneficiaryStatus.UNKNOWN, "Plan beneficiary is not registered"); return _beneficiaries[beneficiary]; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Calculates and returns the vested token amount. */ function calculateVestedAmount(address wallet) public view returns (uint256 vestedAmount) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[wallet]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; vestedAmount = 0; uint256 currentMonth = timeHelpers.getCurrentMonth(); if (currentMonth >= beneficiaryPlan.startMonth.add(planParams.vestingCliff)) { vestedAmount = beneficiaryPlan.amountAfterLockup; if (currentMonth >= beneficiaryPlan.startMonth.add(planParams.totalVestingDuration)) { vestedAmount = beneficiaryPlan.fullAmount; } else { uint256 payment = _getSinglePaymentSize( wallet, beneficiaryPlan.fullAmount, beneficiaryPlan.amountAfterLockup ); vestedAmount = vestedAmount.add(payment.mul(_getNumberOfCompletedVestingEvents(wallet))); } } } /** * @dev Returns the number of vesting events that have completed. */ function _getNumberOfCompletedVestingEvents(address wallet) internal view returns (uint) { ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); Beneficiary memory beneficiaryPlan = _beneficiaries[wallet]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; uint256 firstVestingMonth = beneficiaryPlan.startMonth.add(planParams.vestingCliff); if (now < timeHelpers.monthToTimestamp(firstVestingMonth)) { return 0; } else { uint256 currentMonth = timeHelpers.getCurrentMonth(); if (planParams.vestingIntervalTimeUnit == TimeUnit.DAY) { return _daysBetweenMonths(firstVestingMonth, currentMonth) .add( now .sub(timeHelpers.monthToTimestamp(currentMonth)) .div(_SECONDS_PER_DAY) ) .div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.MONTH) { return currentMonth .sub(firstVestingMonth) .div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.YEAR) { return currentMonth .sub(firstVestingMonth) .div(_MONTHS_PER_YEAR) .div(planParams.vestingInterval); } else { revert("Unknown time unit"); } } } /** * @dev Returns the number of total vesting events. */ function _getNumberOfAllVestingEvents(address wallet) internal view returns (uint) { Beneficiary memory beneficiaryPlan = _beneficiaries[wallet]; Plan memory planParams = _plans[beneficiaryPlan.planId - 1]; if (planParams.vestingIntervalTimeUnit == TimeUnit.DAY) { return _daysBetweenMonths( beneficiaryPlan.startMonth.add(planParams.vestingCliff), beneficiaryPlan.startMonth.add(planParams.totalVestingDuration) ).div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.MONTH) { return planParams.totalVestingDuration .sub(planParams.vestingCliff) .div(planParams.vestingInterval); } else if (planParams.vestingIntervalTimeUnit == TimeUnit.YEAR) { return planParams.totalVestingDuration .sub(planParams.vestingCliff) .div(_MONTHS_PER_YEAR) .div(planParams.vestingInterval); } else { revert("Unknown time unit"); } } /** * @dev Returns the amount of tokens that are unlocked in each vesting * period. */ function _getSinglePaymentSize( address wallet, uint256 fullAmount, uint256 afterLockupPeriodAmount ) internal view returns(uint) { return fullAmount.sub(afterLockupPeriodAmount).div(_getNumberOfAllVestingEvents(wallet)); } function _deployEscrow(address beneficiary) private returns (Escrow) { // TODO: replace with ProxyFactory when @openzeppelin/upgrades will be compatible with solidity 0.6 IProxyFactory proxyFactory = IProxyFactory(contractManager.getContract("ProxyFactory")); Escrow escrow = Escrow(contractManager.getContract("Escrow")); // TODO: replace with ProxyAdmin when @openzeppelin/upgrades will be compatible with solidity 0.6 IProxyAdmin proxyAdmin = IProxyAdmin(contractManager.getContract("ProxyAdmin")); return Escrow( proxyFactory.deploy( uint256(bytes32(bytes20(beneficiary))), proxyAdmin.getProxyImplementation(address(escrow)), address(proxyAdmin), abi.encodeWithSelector( Escrow.initialize.selector, address(contractManager), beneficiary ) ) ); } function _daysBetweenMonths(uint256 beginMonth, uint256 endMonth) private view returns (uint256) { assert(beginMonth <= endMonth); ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers")); uint256 beginTimestamp = timeHelpers.monthToTimestamp(beginMonth); uint256 endTimestamp = timeHelpers.monthToTimestamp(endMonth); uint256 secondsPassed = endTimestamp.sub(beginTimestamp); require(secondsPassed.mod(_SECONDS_PER_DAY) == 0, "Internal error in calendar"); return secondsPassed.div(_SECONDS_PER_DAY); } /** * @dev returns time of next vest in abstract time units named "step" * Examples: * if current step is 5 and vesting interval is 7 function returns 7. * if current step is 17 and vesting interval is 7 function returns 21. */ function _calculateNextVestingStep(uint256 currentStep, uint256 vestingInterval) private pure returns (uint256) { return currentStep .add(vestingInterval) .sub( currentStep.mod(vestingInterval) ); } } // SPDX-License-Identifier: AGPL-3.0-only /* IProxyFactory.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // TODO: Remove it when @openzeppelin/upgrades will be compatible with solidity 0.6 interface IProxyFactory { function deploy(uint256 _salt, address _logic, address _admin, bytes memory _data) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* IProxyAdmin.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // TODO: Remove it when @openzeppelin/upgrades will be compatible with solidity 0.6 interface IProxyAdmin { function getProxyImplementation(address proxy) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* ITimeHelpers.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Time Helpers Interface * @dev Interface of Time Helper functions of the Time Helpers SKALE Allocator * contract. */ interface ITimeHelpers { function getCurrentMonth() external view returns (uint); function monthToTimestamp(uint month) external view returns (uint timestamp); } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./interfaces/IContractManager.sol"; /** * @title Permissions - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; IContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = IContractManager(contractManagerAddress); } } 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Contract Manager * @dev This contract is the main contract for upgradeable approach. This * contract contains the current mapping from contract IDs (in the form of * human-readable strings) to addresses. */ interface IContractManager { /** * @dev Returns the contract address of a given contract name. * * Requirements: * * - Contract mapping must exist. */ function getContract(string calldata name) external view returns (address contractAddress); } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolderMock.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "../Permissions.sol"; /** * @dev Interface of Delegatable Token operations. */ contract ConstantsHolderMock is Permissions { uint256 public launchTimestamp; function setLaunchTimestamp(uint256 timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title Contract Manager * @dev This contract is the main contract for upgradeable approach. This * contract contains the current mapping from contract IDs (in the form of * human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows Owner to add contract to mapping of actual contract addresses * * Emits a {ContractUpgraded} event. * * Requirements: * * - Contract address is non-zero. * - Contract address is not already added. * - Contract contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns the contract address of a given contract name. * * Requirements: * * - Contract mapping must exist. */ function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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: AGPL-3.0-only /* StringUtils.sol - SKALE Allocator Copyright (C) 2020-Present SKALE Labs @author Vadim Yavorsky SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint256 k = 0; uint256 i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationControllerTester.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/IDelegationController.sol"; import "./interfaces/ILocker.sol"; import "./TokenStateTester.sol"; import "./SkaleTokenTester.sol"; contract DelegationControllerTester is Permissions, IDelegationController, ILocker { struct Delegation { address holder; uint256 amount; } mapping (address => uint) private _locked; Delegation[] private _delegations; function delegate( uint256 , uint256 amount, uint256 , string calldata ) external override { SkaleTokenTester skaleToken = SkaleTokenTester(contractManager.getContract("SkaleToken")); TokenStateTester tokenState = TokenStateTester(contractManager.getContract("TokenState")); _delegations.push(Delegation({ holder: msg.sender, amount: amount })); _locked[msg.sender] += amount; uint256 holderBalance = skaleToken.balanceOf(msg.sender); uint256 forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); } function requestUndelegation(uint256 delegationId) external override { address holder = _delegations[delegationId].holder; _locked[holder] -= _delegations[delegationId].amount; } function cancelPendingDelegation(uint delegationId) external override { address holder = _delegations[delegationId].holder; _locked[holder] -= _delegations[delegationId].amount; } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } function _getAndUpdateLockedAmount(address wallet) private view returns (uint) { return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of Locker functions of the {TokenState} contract. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. See {DelegationController}; * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator {getAndUpdateLockedAmount}. This lock enforces * Proof-of-Use requirements. See {TokenLaunchLocker}; and, * * - Tokens that are neither transferable nor delegatable * {getAndUpdateForbiddenForDelegationAmount}. This lock enforces slashing. * See {Punisher}. */ interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ITokenState.sol"; import "./interfaces/ILocker.sol"; contract TokenStateTester is Permissions, ITokenState { string[] private _lockers; function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint) { uint256 forbidden = 0; for (uint256 i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint256 locked = 0; for (uint256 i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/ERC777.sol"; import "../Permissions.sol"; import "../interfaces/delegation/ITokenState.sol"; contract SkaleTokenTester is ERC777UpgradeSafe, Permissions { uint256 public constant CAP = 7 * 1e9 * (10 ** 18); // the maximum amount of tokens that can ever be created constructor( address contractManagerAddress, string memory name, string memory symbol, address[] memory defOp ) public { ERC777UpgradeSafe.__ERC777_init(name, symbol, defOp); Permissions.initialize(contractManagerAddress); } function mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) external onlyOwner returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } function getAndUpdateDelegatedAmount(address) pure external returns (uint) { return 0; } function getAndUpdateSlashedAmount(address) pure external returns (uint) { return 0; } function getAndUpdateLockedAmount(address wallet) public returns (uint) { ITokenState tokenState = ITokenState(contractManager.getContract("TokenState")); return tokenState.getAndUpdateLockedAmount(wallet); } function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint256 locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC777.sol"; import "./IERC777Recipient.sol"; import "./IERC777Sender.sol"; import "../../token/ERC20/IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../introspection/IERC1820Registry.sol"; import "../../Initializable.sol"; /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777UpgradeSafe is Initializable, ContextUpgradeSafe, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ function __ERC777_init( string memory name, string memory symbol, address[] memory defaultOperators ) internal initializer { __Context_init_unchained(); __ERC777_init_unchained(name, symbol, defaultOperators); } function __ERC777_init_unchained( string memory name, string memory symbol, address[] memory defaultOperators ) internal initializer { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), amount); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) internal { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 tokenId) internal virtual { } uint256[41] private __gap; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* DistributorMock.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../interfaces/delegation/IDistributor.sol"; contract DistributorMock is IDistributor, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); IERC20 public skaleToken; // wallet => validatorId => tokens mapping (address => mapping (uint256 => uint)) public approved; constructor (address skaleTokenAddress) public { skaleToken = IERC20(skaleTokenAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function withdrawBounty(uint256 validatorId, address to) external override { uint256 bounty = approved[msg.sender][validatorId]; delete approved[msg.sender][validatorId]; require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32 * 2, "Data length is incorrect"); (uint256 validatorId, address wallet) = abi.decode(userData, (uint, address)); _payBounty(wallet, validatorId, amount); } // private function _payBounty(address wallet, uint256 validatorId, uint256 amount) private { approved[wallet][validatorId] += amount; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./interfaces/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* ProxyFactoryMock.sol - SKALE Allocator Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/openzeppelin/IProxyFactory.sol"; import "../interfaces/openzeppelin/IProxyAdmin.sol"; contract ProxyMock { bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; constructor(address implementation, bytes memory _data) public { _setImplementation(implementation); if(_data.length > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success,) = implementation.delegatecall(_data); require(success); } } fallback () payable external { _delegate(_implementation()); } function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _implementation() internal view returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } function _setImplementation(address newImplementation) internal { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } contract ProxyFactoryMock is IProxyFactory, IProxyAdmin { address public implementation; function deploy(uint256, address _logic, address, bytes memory _data) external override returns (address) { return address(new ProxyMock(_logic, _data)); } function setImplementation(address _implementation) external { implementation = _implementation; } function getProxyImplementation(address) external view override returns (address) { return implementation; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { uint256 year; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { uint256 year; uint256 month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.0; contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./thirdparty/BokkyPooBahsDateTimeLibrary.sol"; import "../interfaces/ITimeHelpers.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpersTester is ITimeHelpers { using SafeMath for uint; uint256 constant private _ZERO_YEAR = 2020; function getCurrentMonth() external view override returns (uint) { return timestampToMonth(now); } function timestampToMonth(uint256 timestamp) public pure returns (uint) { uint256 year; uint256 month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint256 month) public view override returns (uint256 timestamp) { uint256 year = _ZERO_YEAR; uint256 _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ITokenLaunchManager.sol - SKALE Allocator Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Allocator 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. SKALE Allocator 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 SKALE Allocator. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; // import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "../Permissions.sol"; /** * @dev Interface of Delegatable Token operations. */ contract TokenLaunchManagerTester is Permissions { bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE"); function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } }
See {IERC777-granularity}. This implementation always returns `1`./
function granularity() public view override returns (uint256) { return 1; }
19,791
pragma solidity ^0.4.18; interface tokenRecipient{ function receiveApproval(address _from,uint256 _value,address _token,bytes _extraData) external ; } contract GrowToken{ //public var address public owner; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public sellPrice; //grow to wei not eth! uint256 public buyPrice; bool public sellOpen; bool public buyOpen; //store token data set mapping(address => uint256) public balanceOf; //transition limite mapping(address => mapping(address => uint256)) public allowance; //freeze account mapping(address=>bool) public frozenAccount; //event for transition event Transfer(address indexed from,address indexed to , uint256 value); //event for allowance event Approval(address indexed owner,address indexed spender,uint256 value); //event for freeze/unfreeze Account event FrozenFunds(address target,bool freeze); //TODO event for sell token , do&#39;t need it now event SellToken(address seller,uint256 sellPrice, uint256 amount,uint256 getEth); //TODO event for buy token , do&#39;t need it now event BuyToken(address buyer,uint256 buyPrice,uint256 amount,uint256 spendEth); modifier onlyOwner { require(msg.sender == owner); _; } //func constructor function GrowToken() public { owner = 0x757D7FbB9822b5033a6BBD4e17F95714942f921f; name = "GROWCHAIN"; symbol = "GROW"; decimals = 8; totalSupply = 5000000000 * 10 ** uint256(8); //init totalSupply to map(db) balanceOf[owner] = totalSupply; } function () public payable { if(msg.sender!=owner){ _buy(); } } // public functions // 1 Transfer tokens function transfer(address _to,uint256 _value) public{ require(!frozenAccount[msg.sender]); if(_to == address(this)){ _sell(msg.sender,_value); }else{ _transfer(msg.sender,_to,_value); } } // 2 Transfer Other&#39;s tokens ,who had approve some token to me function transferFrom(address _from,address _to,uint256 _value) public returns (bool success){ //validate the allowance require(!frozenAccount[_from]&&!frozenAccount[msg.sender]); require(_value<=allowance[_from][msg.sender]); //do action :sub allowance and do transfer allowance[_from][msg.sender] -= _value; if(_to == address(this)){ _sell(_from,_value); }else { _transfer(_from,_to,_value); } return true; } //A is msg.sender or i //B is the person who has approve me to use his token or _from //C is the receipient or _to // 3 set allowance for other address,like B approve A(_spender) to use his token function approve(address _spender,uint256 _value) public returns (bool success){ require(!frozenAccount[msg.sender]); allowance[msg.sender][_spender] = _value; return true; } // 4 allowance and notify the receipient/spender function approveAndCall(address _spender,uint256 _value,bytes _extraData) public returns (bool success){ require(!frozenAccount[msg.sender]); tokenRecipient spender = tokenRecipient(_spender); if(approve(_spender,_value)){ spender.receiveApproval(msg.sender,_value,this,_extraData); return true; } } // onlyOwner function // 11 freeze or unfreeze account function freezeAccount(address target,bool freeze) onlyOwner public{ require(target!=owner); frozenAccount[target] = freeze; FrozenFunds(target,freeze); } // 12 transfer contract Ownership to newOwner and transfer all balanceOf oldOwner to newOwner function transferOwnership(address newOwner) onlyOwner public{ _transfer(owner,newOwner,balanceOf[owner]); owner = newOwner; } // 13 set prices for sellPrice or buyPrice function setPrices(uint256 newSellPrice,uint256 newBuyPrice) onlyOwner public{ sellPrice = newSellPrice; buyPrice = newBuyPrice; } // 14 open/close user to buy token function setBuyOpen(bool newBuyOpen) onlyOwner public{ require(buyPrice>0); buyOpen = newBuyOpen; } // 15 open/close user to sell token function setSellOpen(bool newSellOpen) onlyOwner public{ require(sellPrice>0); sellOpen = newSellOpen; } // 16 transfer eth back to owner function transferEth(uint256 amount) onlyOwner public{ msg.sender.transfer(amount*10**uint256(18)); } //internal transfer function // 1 _transfer function _transfer(address _from,address _to, uint256 _value) internal { //validate input and other internal limites require(_to != 0x0);//check to address require(balanceOf[_from] >= _value);//check from address has enough balance require(balanceOf[_to] + _value >balanceOf[_to]);//after transfer the balance of _to address is ok ,no overflow uint256 previousBalances = balanceOf[_from]+balanceOf[_to];//store it for add asset to power the security //do transfer:sub from _from address,and add to the _to address balanceOf[_from] -= _value; balanceOf[_to] += _value; //after transfer: emit transfer event,and add asset for security Transfer(_from,_to,_value); assert(balanceOf[_from]+balanceOf[_to] == previousBalances); } // 2 _buy function _buy() internal returns (uint256 amount){ require(buyOpen); require(buyPrice>0); require(msg.value>0); amount = msg.value / buyPrice; // calculates the amount _transfer(owner,msg.sender,amount); BuyToken(msg.sender,buyPrice,amount,msg.value); return amount; // ends function and returns } // 3 _sell function _sell(address _from,uint256 amount) internal returns (uint256 revenue){ require(sellOpen); require(!frozenAccount[_from]); require(amount>0); require(sellPrice>0); require(_from!=owner); _transfer(_from,owner,amount); revenue = amount * sellPrice; _from.transfer(revenue); // sends ether to the seller: it&#39;s important to do this last to prevent recursion attacks SellToken(_from,sellPrice,amount,revenue); return revenue; // ends function and returns } }
3 set allowance for other address,like B approve A(_spender) to use his token
function approve(address _spender,uint256 _value) public returns (bool success){ require(!frozenAccount[msg.sender]); allowance[msg.sender][_spender] = _value; return true; }
7,811,084
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library ExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; InnerOp.Data[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new InnerOp.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.path[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); for(uint256 i4 = 0; i4 < input.path.length; i4++) { output.path.push(input.path[i4]); } } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ExistenceProof library NonExistenceProof { //struct definition struct Data { bytes key; ExistenceProof.Data left; ExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; ExistenceProof.store(input.left, output.left); ExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library NonExistenceProof library CommitmentProof { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; BatchProof.Data batch; CompressedBatchProof.Data compressed; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_batch(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_compressed(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_batch( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchProof.Data memory x, uint256 sz) = _decode_BatchProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.batch = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_compressed( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchProof.Data memory x, uint256 sz) = _decode_CompressedBatchProof(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.compressed = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchProof(uint256 p, bytes memory bs) internal pure returns (BatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchProof.Data memory r, ) = BatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchProof(uint256 p, bytes memory bs) internal pure returns (CompressedBatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchProof.Data memory r, ) = CompressedBatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BatchProof._encode_nested(r.batch, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedBatchProof._encode_nested(r.compressed, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); e += 1 + ProtoBufRuntime._sz_lendelim(BatchProof._estimate(r.batch)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchProof._estimate(r.compressed)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); BatchProof.store(input.batch, output.batch); CompressedBatchProof.store(input.compressed, output.compressed); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitmentProof library LeafOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_key; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_value; PROOFS_PROTO_GLOBAL_ENUMS.LengthOp length; bytes prefix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[6] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prehash_key(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_prehash_value(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_prefix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_key( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[2] += 1; } else { r.prehash_key = x; if(counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_value( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[3] += 1; } else { r.prehash_value = x; if(counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_length( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.LengthOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_LengthOp(tmp); if (isNil(r)) { counters[4] += 1; } else { r.length = x; if(counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.prefix = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (uint(r.prehash_key) != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_key = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_key, pointer, bs); } if (uint(r.prehash_value) != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_value = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_value, pointer, bs); } if (uint(r.length) != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_length = PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length); pointer += ProtoBufRuntime._encode_enum(_enum_length, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (uint(r.prehash_key) != 0) { return false; } if (uint(r.prehash_value) != 0) { return false; } if (uint(r.length) != 0) { return false; } if (r.prefix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prehash_key = input.prehash_key; output.prehash_value = input.prehash_value; output.length = input.length; output.prefix = input.prefix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library LeafOp library InnerOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; bytes prefix; bytes suffix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prefix(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_suffix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.prefix = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_suffix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.suffix = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } if (r.suffix.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.suffix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.suffix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (r.prefix.length != 0) { return false; } if (r.suffix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prefix = input.prefix; output.suffix = input.suffix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerOp library ProofSpec { //struct definition struct Data { LeafOp.Data leaf_spec; InnerSpec.Data inner_spec; int32 max_depth; int32 min_depth; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_leaf_spec(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_inner_spec(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_max_depth(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_min_depth(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.leaf_spec = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_inner_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerSpec.Data memory x, uint256 sz) = _decode_InnerSpec(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.inner_spec = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.max_depth = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.min_depth = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerSpec(uint256 p, bytes memory bs) internal pure returns (InnerSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerSpec.Data memory r, ) = InnerSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf_spec, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += InnerSpec._encode_nested(r.inner_spec, pointer, bs); if (r.max_depth != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_depth, pointer, bs); } if (r.min_depth != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_depth, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec)); e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec)); e += 1 + ProtoBufRuntime._sz_int32(r.max_depth); e += 1 + ProtoBufRuntime._sz_int32(r.min_depth); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.max_depth != 0) { return false; } if (r.min_depth != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { LeafOp.store(input.leaf_spec, output.leaf_spec); InnerSpec.store(input.inner_spec, output.inner_spec); output.max_depth = input.max_depth; output.min_depth = input.min_depth; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ProofSpec library InnerSpec { //struct definition struct Data { int32[] child_order; int32 child_size; int32 min_prefix_length; int32 max_prefix_length; bytes empty_child; PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.child_order = new int32[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_order( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.child_order[r.child_order.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_size( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.child_size = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.min_prefix_length = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.max_prefix_length = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_empty_child( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.empty_child = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[6] += 1; } else { r.hash = x; if(counters[6] > 0) counters[6] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.child_order.length != 0) { for(i = 0; i < r.child_order.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.child_order[i], pointer, bs); } } if (r.child_size != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.child_size, pointer, bs); } if (r.min_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_prefix_length, pointer, bs); } if (r.max_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_prefix_length, pointer, bs); } if (r.empty_child.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.empty_child, pointer, bs); } if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.child_order.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.child_order[i]); } e += 1 + ProtoBufRuntime._sz_int32(r.child_size); e += 1 + ProtoBufRuntime._sz_int32(r.min_prefix_length); e += 1 + ProtoBufRuntime._sz_int32(r.max_prefix_length); e += 1 + ProtoBufRuntime._sz_lendelim(r.empty_child.length); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.child_order.length != 0) { return false; } if (r.child_size != 0) { return false; } if (r.min_prefix_length != 0) { return false; } if (r.max_prefix_length != 0) { return false; } if (r.empty_child.length != 0) { return false; } if (uint(r.hash) != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.child_order = input.child_order; output.child_size = input.child_size; output.min_prefix_length = input.min_prefix_length; output.max_prefix_length = input.max_prefix_length; output.empty_child = input.empty_child; output.hash = input.hash; } //array helpers for ChildOrder /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addChildOrder(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.child_order.length + 1); for (uint256 i = 0; i < self.child_order.length; i++) { tmp[i] = self.child_order[i]; } tmp[self.child_order.length] = value; self.child_order = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerSpec library BatchProof { //struct definition struct Data { BatchEntry.Data[] entries; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new BatchEntry.Data[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchEntry.Data memory x, uint256 sz) = _decode_BatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchEntry(uint256 p, bytes memory bs) internal pure returns (BatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchEntry.Data memory r, ) = BatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += BatchEntry._encode_nested(r.entries[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(BatchEntry._estimate(r.entries[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, BatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ BatchEntry.Data[] memory tmp = new BatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchProof library BatchEntry { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchEntry library CompressedBatchProof { //struct definition struct Data { CompressedBatchEntry.Data[] entries; InnerOp.Data[] lookup_inners; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new CompressedBatchEntry.Data[](counters[1]); r.lookup_inners = new InnerOp.Data[](counters[2]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchEntry.Data memory x, uint256 sz) = _decode_CompressedBatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_lookup_inners( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.lookup_inners[r.lookup_inners.length - counters[2]] = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchEntry(uint256 p, bytes memory bs) internal pure returns (CompressedBatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchEntry.Data memory r, ) = CompressedBatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CompressedBatchEntry._encode_nested(r.entries[i], pointer, bs); } } if (r.lookup_inners.length != 0) { for(i = 0; i < r.lookup_inners.length; i++) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.lookup_inners[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchEntry._estimate(r.entries[i])); } for(i = 0; i < r.lookup_inners.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.lookup_inners[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } if (r.lookup_inners.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } for(uint256 i2 = 0; i2 < input.lookup_inners.length; i2++) { output.lookup_inners.push(input.lookup_inners[i2]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, CompressedBatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CompressedBatchEntry.Data[] memory tmp = new CompressedBatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //array helpers for LookupInners /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addLookupInners(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.lookup_inners.length + 1); for (uint256 i = 0; i < self.lookup_inners.length; i++) { tmp[i] = self.lookup_inners[i]; } tmp[self.lookup_inners.length] = value; self.lookup_inners = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchProof library CompressedBatchEntry { //struct definition struct Data { CompressedExistenceProof.Data exist; CompressedNonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedNonExistenceProof.Data memory x, uint256 sz) = _decode_CompressedNonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedNonExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedNonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedNonExistenceProof.Data memory r, ) = CompressedNonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedNonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedNonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { CompressedExistenceProof.store(input.exist, output.exist); CompressedNonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchEntry library CompressedExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; int32[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new int32[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.path[i]); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); output.path = input.path; } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedExistenceProof library CompressedNonExistenceProof { //struct definition struct Data { bytes key; CompressedExistenceProof.Data left; CompressedExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; CompressedExistenceProof.store(input.left, output.left); CompressedExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedNonExistenceProof library PROOFS_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum HashOp { NO_HASH, SHA256, SHA512, KECCAK, RIPEMD160, BITCOIN } // Solidity enum encoder function encode_HashOp(HashOp x) internal pure returns (int32) { if (x == HashOp.NO_HASH) { return 0; } if (x == HashOp.SHA256) { return 1; } if (x == HashOp.SHA512) { return 2; } if (x == HashOp.KECCAK) { return 3; } if (x == HashOp.RIPEMD160) { return 4; } if (x == HashOp.BITCOIN) { return 5; } revert(); } // Solidity enum decoder function decode_HashOp(int64 x) internal pure returns (HashOp) { if (x == 0) { return HashOp.NO_HASH; } if (x == 1) { return HashOp.SHA256; } if (x == 2) { return HashOp.SHA512; } if (x == 3) { return HashOp.KECCAK; } if (x == 4) { return HashOp.RIPEMD160; } if (x == 5) { return HashOp.BITCOIN; } revert(); } // Solidity enum definitions enum LengthOp { NO_PREFIX, VAR_PROTO, VAR_RLP, FIXED32_BIG, FIXED32_LITTLE, FIXED64_BIG, FIXED64_LITTLE, REQUIRE_32_BYTES, REQUIRE_64_BYTES } // Solidity enum encoder function encode_LengthOp(LengthOp x) internal pure returns (int32) { if (x == LengthOp.NO_PREFIX) { return 0; } if (x == LengthOp.VAR_PROTO) { return 1; } if (x == LengthOp.VAR_RLP) { return 2; } if (x == LengthOp.FIXED32_BIG) { return 3; } if (x == LengthOp.FIXED32_LITTLE) { return 4; } if (x == LengthOp.FIXED64_BIG) { return 5; } if (x == LengthOp.FIXED64_LITTLE) { return 6; } if (x == LengthOp.REQUIRE_32_BYTES) { return 7; } if (x == LengthOp.REQUIRE_64_BYTES) { return 8; } revert(); } // Solidity enum decoder function decode_LengthOp(int64 x) internal pure returns (LengthOp) { if (x == 0) { return LengthOp.NO_PREFIX; } if (x == 1) { return LengthOp.VAR_PROTO; } if (x == 2) { return LengthOp.VAR_RLP; } if (x == 3) { return LengthOp.FIXED32_BIG; } if (x == 4) { return LengthOp.FIXED32_LITTLE; } if (x == 5) { return LengthOp.FIXED64_BIG; } if (x == 6) { return LengthOp.FIXED64_LITTLE; } if (x == 7) { return LengthOp.REQUIRE_32_BYTES; } if (x == 8) { return LengthOp.REQUIRE_64_BYTES; } revert(); } } //library PROOFS_PROTO_GLOBAL_ENUMS
Solidity enum encoder
function encode_HashOp(HashOp x) internal pure returns (int32) { if (x == HashOp.NO_HASH) { return 0; } if (x == HashOp.SHA256) { return 1; } if (x == HashOp.SHA512) { return 2; } if (x == HashOp.KECCAK) { return 3; } if (x == HashOp.RIPEMD160) { return 4; } if (x == HashOp.BITCOIN) { return 5; } revert(); }
13,050,690
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import './SafeMath32.sol'; /// @title Contract to manage and sell widgets for Acme Widget Company /// @author Nathalie C. Chan King Choy contract AcmeWidgetCo { using SafeMath for uint256; using SafeMath32 for uint32; //=========================================== // Struct definitions //=========================================== // The information about a single widget struct WidgetData { uint32 serialNumber; uint8 factoryMadeAt; uint8 siteTestedAt; uint32 testResults; // bit == 1 => that test passed, 0 => test failed // e.g. testResults == 0xFFFFFFFF means all 32 tests passed // e.g. testResults == 0xFFFF0000 means only the first 16 tests passed } // Assumption: Customer will buy >1 widget in an order. // The information for an order of widgets from a particular bin. // Widgets are sold in array index order // e.g. Customer buys 5 widgets. If [1] was the last widget sold in that // bin, then firstIndex is [2], lastIndex is [6] for this order. struct WidgetOrderFill { uint8 bin; // Indices into corresponding bin of widgets uint32 firstIndex; uint32 lastIndex; } //=========================================== // Contract variables //=========================================== // Circuit breaker bool public stopContract; // Lists of users by role mapping (address => uint8) public addr2Role; // Enum may seem appropriate, but you have to document the decoding anyway // because the enum isn't accessible in JavaScript, so skip using enum. // This is how to decode: // Admin = 1 // Tester = 2 // Sales Distributor = 3 // Customer = 4 // Assumption: During the life of this contract Acme won't ever reach >256 sites // Stores names of factories and test sites string[] public factoryList; string[] public testSiteList; uint8 public factoryCount; uint8 public testSiteCount; // Used to ensure we don't add a duplicate factory or test site // Uses the keccak256 hash of the string for the lookup // Store the index into the string array for that name mapping (bytes32 => uint8) public factoryMapping; mapping (bytes32 => uint8) public testSiteMapping; // Track the widgets. Map the serial number to position in widgetList // Assumption: We won't have more than 4 billion widgets // Bin0 is unsellable widgets (i.e. did not have the correct sets of // passing test results. So, not all 0 indices are populated b/c N/A. // Bin1 has most functionality, Bin2 a bit less, Bin3 even less WidgetData[] public widgetList; mapping (uint32 => uint32) public widgetSerialMapping; uint32 public widgetCount; uint32[4] public binMask; // What tests must pass to be in each bin. uint256[4] public binUnitPrice; // in wei uint32[] public bin1Widgets; // Array of indices into widgetList uint32[] public bin2Widgets; uint32[] public bin3Widgets; uint32[4] public binWidgetCount; // HACK: Because using uint instead of int, widget[0] never really gets sold // TODO: Deal with that later if time allows uint32[4] public lastWidgetSoldInBin; // Index of last sold in that bin mapping (address => WidgetOrderFill[]) public customerWidgetMapping; // Who owns each widget in widgetList //=========================================== // Events //=========================================== event NewAdmin(address indexed _newAdminRegistered); event NewTester(address indexed _newTesterRegistered); event NewSalesDistributor(address indexed _newSalesDistributorRegistered); event NewCustomer(address indexed _newCustomerRegistered); event NewFactory(uint8 indexed _factoryCount, string _factory); event NewTestSite(uint8 indexed _testSiteCount, string _testSite); event NewTestedWidget(uint32 indexed _serial, uint8 indexed _factory, uint8 _testSite, uint32 _results, uint32 _widgetCount, uint8 indexed _bin, uint32 _binCount); event NewUnitPrice(uint8 indexed _bin, uint256 _newPrice, address indexed _salesDistributor); event NewBinMask(uint8 indexed _bin, uint32 _newBinMask, address indexed _salesDistributor); event WidgetSale(uint8 indexed _bin, uint32 _quantity, address indexed _customer, uint256 _totalAmtPaid); event FundsWithdrawn(address indexed _withdrawer, uint256 _amt); //=========================================== // Modifiers //=========================================== modifier onlyAdmin { require( (addr2Role[msg.sender] == 1), "Only Admins can run this function." ); _; } modifier onlyTester { require( (addr2Role[msg.sender] == 2), "Only Testers can run this function." ); _; } modifier onlySalesDistributor { require( (addr2Role[msg.sender] == 3), "Only Sales Distributors can run this function." ); _; } modifier onlyCustomer { require( (addr2Role[msg.sender] == 4), "Only Customers can run this function." ); _; } // Circuit breaker modifier stopInEmergency { require(!stopContract, "Emergency: Contract is stopped."); _; } modifier onlyInEmergency { require(stopContract, "Not an emergency. This function is only for emergencies."); _; } //=========================================== // constructor //=========================================== /// @notice Set up initial conditions for the contract, on deployment constructor() public { // Circuit breaker stopContract = false; // The first admin is the deployer of the contract addr2Role[msg.sender] = 1; // These values can only be changed by Sales Distributors binUnitPrice[1] = 0.1 ether; binUnitPrice[2] = 0.05 ether; binUnitPrice[3] = 0.01 ether; binMask[1] = 0xFFFFFFFF; binMask[2] = 0xFFFF0000; binMask[3] = 0xFF000000; } // fallback function (if exists) //=========================================== // public //=========================================== //------------------------- // Admin functions //------------------------- /// @notice Circuit breaker enable - start emergency mode function beginEmergency() public onlyAdmin { stopContract = true; } /// @notice Circuit breaker disable - end emergency mode function endEmergency() public onlyAdmin { stopContract = false; } /// @notice Report contract balance for withdrawal possibility function getContractBalance() constant public onlyAdmin returns (uint) { return address(this).balance; } /// @notice Allow admin to withdraw funds from contract /// @dev TODO Create Finance role for that, if time allows /// @dev Using transfer protects against re-entrancy /// @param _amtToWithdraw How much to withdraw function withdrawFunds(uint256 _amtToWithdraw) public onlyAdmin { require(_amtToWithdraw <= address(this).balance, "Trying to withdraw more than contract balance."); msg.sender.transfer(_amtToWithdraw); emit FundsWithdrawn(msg.sender, _amtToWithdraw); } // Functions to add to user lists /// @notice Admin can add another admin /// @dev Admin has privileges for adding users, sites, or stopping contract /// @param _newAdmin is Ethereum address of the new admin function registerAdmin(address _newAdmin) public onlyAdmin { require(addr2Role[_newAdmin] == 0); addr2Role[_newAdmin] = 1; emit NewAdmin(_newAdmin); } /// @notice Admin can add another tester /// @dev Tester has privileges to record test results for widgets /// @param _newTester is Ethereum address of the new tester function registerTester(address _newTester) public onlyAdmin { require(addr2Role[_newTester] == 0); addr2Role[_newTester] = 2; emit NewTester(_newTester); } /// @notice Admin can add another sales distributor /// @dev Sales dist. has privileges to update bin masks and unit prices /// @param _newSalesDistributor is Ethereum address of the new sales dist. function registerSalesDistributor(address _newSalesDistributor) public onlyAdmin { require(addr2Role[_newSalesDistributor] == 0); addr2Role[_newSalesDistributor] = 3; emit NewSalesDistributor(_newSalesDistributor); } /// @notice Admin can add another customer /// @dev Customer has privileges to buy widgets /// @param _newCustomer is Ethereum address of the new customer function registerCustomer(address _newCustomer) public onlyAdmin { require(addr2Role[_newCustomer] == 0); addr2Role[_newCustomer] = 4; emit NewCustomer(_newCustomer); } /// @notice Admin can add another factory for tester to choose from /// @dev Won't be added if _factory is already in the list /// @param _factory is the name of the new factory. function addFactory(string _factory) public onlyAdmin { require(factoryCount < 255); // Prevent overflow require(factoryMapping[keccak256(abi.encodePacked(_factory))] == 0); factoryList.push(_factory); factoryMapping[keccak256(abi.encodePacked(_factory))] = factoryCount; factoryCount++; emit NewFactory(factoryCount, _factory); } /// @notice Admin can add another test site for tester to choose from /// @dev Won't be added if _testSite is already in the list /// @param _testSite is the name of the new test site. function addTestSite(string _testSite) public onlyAdmin { require(testSiteCount < 255); // Prevent overflow require(testSiteMapping[keccak256(abi.encodePacked(_testSite))] == 0); testSiteList.push(_testSite); testSiteMapping[keccak256(abi.encodePacked(_testSite))] = testSiteCount; testSiteCount++; emit NewTestSite(testSiteCount, _testSite); } //------------------------- // Tester functions //------------------------- /// @notice Tester records the factory where the widget was made, the site /// where it was tested, and the test results for a given widget serial # /// @dev Won't be added if serial # is already in the list /// @dev TODO: Generalize to N bins if time allows /// @dev TODO: Figure out 2-D arrays if time allows /// @param _serial is the serial number for the widget under test /// @param _factory is the factory where the widget was made /// @param _testSite is the site where the widget was tested /// @param _results is the bit mapping of what tests passed or failed /// bit == 1 => that test passed, 0 => test failed /// e.g. testResults == 0xFFFFFFFF means all 32 tests passed /// e.g. testResults == 0xFFFF0000 means only the first 16 tests passed function recordWidgetTests(uint32 _serial, uint8 _factory, uint8 _testSite, uint32 _results) public onlyTester { require(_factory < factoryCount); // Valid factory require(_testSite < testSiteCount); // Valid test site require(widgetSerialMapping[_serial] == 0); // Widget not already recorded uint8 bin; WidgetData memory w; w.serialNumber = _serial; w.factoryMadeAt = _factory; w.siteTestedAt = _testSite; w.testResults = _results; widgetList.push(w); widgetSerialMapping[_serial] = widgetCount; // Save index for serial # if ((_results & binMask[1]) == binMask[1]) { bin1Widgets.push(widgetCount); bin = 1; } else if ((_results & binMask[2]) == binMask[2]) { bin2Widgets.push(widgetCount); bin = 2; } else if ((_results & binMask[3]) == binMask[3]) { bin3Widgets.push(widgetCount); bin = 3; } else { // Widgets that don't match a bin are too low quality to sell bin = 0; } binWidgetCount[bin]++; widgetCount++; emit NewTestedWidget(_serial, _factory, _testSite, _results, widgetCount, bin, binWidgetCount[bin]); } //------------------------- // Sales distributor functions //------------------------- /// @notice Sales distributor can update the unit price of any of the bins /// @dev TODO: Later generalize to N bins, if time allows /// @param _bin is the bin whose price is getting updated /// @param _newPrice is the new price in wei function updateUnitPrice(uint8 _bin, uint256 _newPrice) public onlySalesDistributor { require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); binUnitPrice[_bin] = _newPrice; emit NewUnitPrice(_bin, _newPrice, msg.sender); } /// @notice Sales distributor can update the mask of any of the bins /// @dev TODO: Later generalize to N bins, if time allows /// @dev Mask is how we know what bin a widget belongs in. Widget must have /// a 1 in its test result in all positions where mask is 1 to get into /// that particular bin /// @param _bin is the bin whose mask is getting updated /// @param _newMask is the new mask value (e.g. 0xFFFFFF00) function updateBinMask(uint8 _bin, uint32 _newMask) public onlySalesDistributor { require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); binMask[_bin] = _newMask; emit NewBinMask(_bin, _newMask, msg.sender); } //------------------------- // Customer functions //------------------------- /// @notice Function for customer to buy widgets from a specific bin /// @dev This function is stopped by the circuit breaker /// @dev TODO: Later generalize to N bins, if time allows /// @dev TODO: Currently doesn't refund any excess if customer overpaid /// @dev TODO: Currently only way to withdraw funds is when killing the contract. /// @param _bin is the bin from which the customer wants to buy widgets /// @param _quantity is the number of widgets to buy function buyWidgets(uint8 _bin, uint32 _quantity) payable public onlyCustomer stopInEmergency { require(_quantity > 0, "Must purchase >0 widgets."); require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); uint32 wCount = binWidgetCount[_bin]; uint32 lastSold = lastWidgetSoldInBin[_bin]; uint256 uPrice = binUnitPrice[_bin]; uint32 stock = wCount.sub(lastSold).sub(1); require((_quantity <= stock), "Insufficient stock. NOTE: widget[0] in each bin is not for sale."); require((uint256(_quantity).mul(uPrice) <= msg.value), "Insufficient funds."); WidgetOrderFill memory w; w.bin = _bin; w.firstIndex = lastSold.add(1); w.lastIndex = lastSold.add(_quantity); customerWidgetMapping[msg.sender].push(w); lastWidgetSoldInBin[_bin] = w.lastIndex; emit WidgetSale(_bin, _quantity, msg.sender, msg.value); } }
Report contract balance for withdrawal possibility
function getContractBalance() constant public onlyAdmin returns (uint) { return address(this).balance; }
12,642,323
./full_match/80001/0xb2EFc086E1A0d029E09C16f14f62E5C6aec59864/sources/contracts/CloudArtworkGenerator.sol
gettheme. This is external because it will be used to compile sky contract as well _index represends the theme id/
function getTheme(uint _index) external view returns (Theme memory theme ) { return themesMap[_index]; }
855,499
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * Minado - Crypto Token Mining & Forging Community * * Minado has been optimized for mining ERC918-compatible tokens via * the InfinityPool; a public storage of mineable ERC-20 tokens. * * Learn more below: * * Official : https://minado.network * Ethereum : https://eips.ethereum.org/EIPS/eip-918 * Github : https://github.com/ethereum/EIPs/pull/918 * Reddit : https://www.reddit.com/r/Tokenmining * * Version 19.7.18 * * Web : https://d14na.org * Email : support@d14na.org */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /******************************************************************************* * * InfinityPool Interface */ contract InfinityPoolInterface { function transfer(address _token, address _to, uint _tokens) external returns (bool success); } /******************************************************************************* * * InfinityWell Interface */ contract InfinityWellInterface { function forgeStones(address _owner, uint _tokens) external returns (bool success); function destroyStones(address _owner, uint _tokens) external returns (bool success); function transferERC20(address _token, address _to, uint _tokens) external returns (bool success); function transferERC721(address _token, address _to, uint256 _tokenId) external returns (bool success); } /******************************************************************************* * * Staek(house) Factory Interface */ contract StaekFactoryInterface { function balanceOf(bytes32 _staekhouseId) public view returns (uint balance); function balanceOf(bytes32 _staekhouseId, address _owner) public view returns (uint balance); function getStaekhouse(bytes32 _staekhouseId, address _staeker) external view returns (address factory, address token, address owner, uint ownerLockTime, uint providerLockTime, uint debtLimit, uint lockInterval, uint balance); } /******************************************************************************* * * @notice Minado - Token Mining Contract * * @dev This is a multi-token mining contract, which manages the proof-of-work * verifications before authorizing the movement of tokens from the * InfinityPool and InfinityWell. */ contract Minado is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /** * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * Zer0netDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'minado'; /** * Large Target * * A big number used for difficulty targeting. * * NOTE: Bitcoin uses `2**224`. */ uint private _MAXIMUM_TARGET = 2**234; /** * Minimum Targets * * Minimum number used for difficulty targeting. */ uint private _MINIMUM_TARGET = 2**16; /** * Set basis-point multiplier. * * NOTE: Used for (integer-based) fractional calculations. */ uint private _BP_MUL = 10000; /* Set InfinityStone decimals. */ uint private _STONE_DECIMALS = 18; /* Set single InfinityStone. */ uint private _SINGLE_STONE = 1 * 10**_STONE_DECIMALS; /** * (Ethereum) Blocks Per Forge * * NOTE: Ethereum blocks take approx 15 seconds each. * 1,000 blocks takes approx 4 hours. */ uint private _BLOCKS_PER_STONE_FORGE = 1000; /** * (Ethereum) Blocks Per Generation * * NOTE: We mirror the Bitcoin POW mining algorithm. * We want miners to spend 10 minutes to mine each 'block'. * (about 40 Ethereum blocks for every 1 Bitcoin block) */ uint BLOCKS_PER_GENERATION = 40; // Mainnet & Ropsten // uint BLOCKS_PER_GENERATION = 120; // Kovan /** * (Mint) Generations Per Re-adjustment * * By default, we automatically trigger a difficulty adjustment * after 144 generations / mints (approx 24 hours). * * Frequent adjustments are especially important with low-liquidity * tokens, which are more susceptible to mining manipulation. * * For additional control, token providers retain the ability to trigger * a difficulty re-calculation at any time. * * NOTE: Bitcoin re-adjusts its difficulty every 2,016 generations, * which occurs approx. every 14 days. */ uint private _DEFAULT_GENERATIONS_PER_ADJUSTMENT = 144; // approx. 24hrs event Claim( address owner, address token, uint amount, address collectible, uint collectibleId ); event Excavate( address indexed token, address indexed miner, uint mintAmount, uint epochCount, bytes32 newChallenge ); event Mint( address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallenge ); event ReCalculate( address token, uint newDifficulty ); event Solution( address indexed token, address indexed miner, uint difficulty, uint nonce, bytes32 challenge, bytes32 newChallenge ); /* Constructor. */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); // _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN // _zer0netDb = Zer0netDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Minado(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * @dev Only allow access to "registered" authorized user/contract. */ modifier onlyTokenProvider( address _token ) { /* Validate authorized token manager. */ require(_zer0netDb.getBool(keccak256(abi.encodePacked( _namespace, '.', msg.sender, '.has.auth.for.', _token ))) == true); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Initialize Token */ function init( address _token, address _provider ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(hash, block.number); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _DEFAULT_GENERATIONS_PER_ADJUSTMENT); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Set mining target. */ // NOTE: This is the default difficulty of 1. _setMiningTarget( _token, _MAXIMUM_TARGET ); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, true); return true; } /** * Mint */ function mint( address _token, bytes32 _digest, uint _nonce ) public returns (bool success) { /* Retrieve the current challenge. */ uint challenge = getChallenge(_token); /* Get mint digest. */ bytes32 digest = getMintDigest( challenge, msg.sender, _nonce ); /* The challenge digest must match the expected. */ if (digest != _digest) { revert('Oops! That solution is NOT valid.'); } /* The digest must be smaller than the target. */ if (uint(digest) > getTarget(_token)) { revert('Oops! That solution is NOT valid.'); } /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', digest, '.solutions' )); /* Retrieve value from Zer0net Db. */ uint solution = _zer0netDb.getUint(hash); /* Validate solution. */ if (solution != 0x0) { revert('Oops! That solution is a DUPLICATE.'); } /* Save this digest to 'solved' solutions. */ _zer0netDb.setUint(hash, uint(digest)); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ uint generation = _zer0netDb.getUint(hash); /* Increment the generation. */ generation = generation.add(1); /* Increment the generation count by 1. */ _zer0netDb.setUint(hash, generation); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(hash); // every so often, readjust difficulty. Dont readjust when deploying if (generation % genPerAdjustment == 0) { _reAdjustDifficulty(_token); } /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /** * Make the latest ethereum block hash a part of the next challenge * for PoW to prevent pre-mining future blocks. Do this last, * since this is a protection mechanism in the mint() function. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Retrieve mining reward. */ // FIXME Add support for percentage reward. uint rewardAmount = getMintFixed(_token); /* Transfer (token) reward to minter. */ _infinityPool().transfer( _token, msg.sender, rewardAmount ); /* Emit log info. */ emit Mint( msg.sender, rewardAmount, generation, blockhash(block.number - 1) // next target ); /* Return success. */ return true; } /** * Test Mint Solution */ function testMint( bytes32 _digest, uint _challenge, address _minter, uint _nonce, uint _target ) public pure returns (bool success) { /* Retrieve digest. */ bytes32 digest = getMintDigest( _challenge, _minter, _nonce ); /* Validate digest. */ // NOTE: Cast type to 256-bit integer if (uint(digest) > _target) { /* Set flag. */ success = false; } else { /* Verify success. */ success = (digest == _digest); } } /** * Re-calculate Difficulty * * Token owner(s) can "manually" trigger the re-calculation of their token, * based on the parameters that have been set. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function reCalculateDifficulty( address _token ) external onlyTokenProvider(_token) returns (bool success) { /* Re-calculate difficulty. */ return _reAdjustDifficulty(_token); } /** * Re-adjust Difficulty * * Re-adjust the target by 5 percent. * (source: https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F) * * NOTE: Assume 240 ethereum blocks per hour (approx. 15/sec) * * NOTE: As of 2017 the bitcoin difficulty was up to 17 zeroes, * it was only 8 in the early days. */ function _reAdjustDifficulty( address _token ) private returns (bool success) { /* Set hash. */ bytes32 lastAdjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Retrieve value from Zer0net Db. */ uint lastAdjustment = _zer0netDb.getUint(lastAdjustmentHash); /* Retrieve value from Zer0net Db. */ uint blocksSinceLastAdjustment = block.number - lastAdjustment; /* Set hash. */ bytes32 adjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(adjustmentHash); /* Calculate number of expected blocks per adjustment. */ uint expectedBlocksPerAdjustment = genPerAdjustment.mul(BLOCKS_PER_GENERATION); /* Retrieve mining target. */ uint miningTarget = getTarget(_token); /* Validate the number of blocks passed; if there were less eth blocks * passed in time than expected, then miners are excavating too quickly. */ if (blocksSinceLastAdjustment < expectedBlocksPerAdjustment) { // NOTE: This number will be an integer greater than 10000. uint excess_block_pct = expectedBlocksPerAdjustment.mul(10000) .div(blocksSinceLastAdjustment); /** * Excess Block Percentage Extra * * For example: * If there were 5% more blocks mined than expected, then this is 500. * If there were 25% more blocks mined than expected, then this is 2500. */ uint excess_block_pct_extra = excess_block_pct.sub(10000); /* Set a maximum difficulty INCREASE of 50%. */ // NOTE: By default, this is within a 24hr period. if (excess_block_pct_extra > 5000) { excess_block_pct_extra = 5000; } /** * Reset the Mining Target * * Calculate the difficulty difference, then SUBTRACT * that value from the current difficulty. */ miningTarget = miningTarget.sub( /* Calculate difficulty difference. */ miningTarget .mul(excess_block_pct_extra) .div(10000) ); } else { // NOTE: This number will be an integer greater than 10000. uint shortage_block_pct = blocksSinceLastAdjustment.mul(10000) .div(expectedBlocksPerAdjustment); /** * Shortage Block Percentage Extra * * For example: * If it took 5% longer to mine than expected, then this is 500. * If it took 25% longer to mine than expected, then this is 2500. */ uint shortage_block_pct_extra = shortage_block_pct.sub(10000); // NOTE: There is NO limit on the amount of difficulty DECREASE. /** * Reset the Mining Target * * Calculate the difficulty difference, then ADD * that value to the current difficulty. */ miningTarget = miningTarget.add( miningTarget .mul(shortage_block_pct_extra) .div(10000) ); } /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(lastAdjustmentHash, block.number); /* Validate TOO SMALL mining target. */ // NOTE: This is very difficult to guess. if (miningTarget < _MINIMUM_TARGET) { miningTarget = _MINIMUM_TARGET; } /* Validate TOO LARGE mining target. */ // NOTE: This is very easy to guess. if (miningTarget > _MAXIMUM_TARGET) { miningTarget = _MAXIMUM_TARGET; } /* Set mining target. */ _setMiningTarget( _token, miningTarget ); /* Return success. */ return true; } /*************************************************************************** * * GETTERS * */ /** * Get Starting Block * * Starting Blocks * --------------- * * First blocks honoring the start of Miss Piggy's celebration year: * - Mainnet : 7,175,716 * - Ropsten : 4,956,268 * - Kovan : 10,283,438 * * NOTE: Pulls value from db `minado.starting.block` using the * respective networks. */ function getStartingBlock() public view returns (uint startingBlock) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.starting.block' )); /* Retrieve value from Zer0net Db. */ startingBlock = _zer0netDb.getUint(hash); } /** * Get minter's mintng address. */ function getMinter() external view returns (address minter) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.minter' )); /* Retrieve value from Zer0net Db. */ minter = _zer0netDb.getAddress(hash); } /** * Get generation details. */ function getGeneration( address _token ) external view returns ( uint generation, uint cycle ) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ generation = _zer0netDb.getUint(hash); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ cycle = _zer0netDb.getUint(hash); } /** * Get Minting FIXED amount */ function getMintFixed( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get Minting PERCENTAGE amount */ function getMintPct( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get (Mining) Challenge * * This is an integer representation of a recent ethereum block hash, * used to prevent pre-mining future blocks. */ function getChallenge( address _token ) public view returns (uint challenge) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Retrieve value from Zer0net Db. */ // NOTE: Convert from bytes to integer. challenge = uint(_bytesToBytes32( _zer0netDb.getBytes(hash) )); } /** * Get (Mining) Difficulty * * The number of zeroes the digest of the PoW solution requires. * (auto adjusts) */ function getDifficulty( address _token ) public view returns (uint difficulty) { /* Caclulate difficulty. */ difficulty = _MAXIMUM_TARGET.div(getTarget(_token)); } /** * Get (Mining) Target */ function getTarget( address _token ) public view returns (uint target) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Retrieve value from Zer0net Db. */ target = _zer0netDb.getUint(hash); } /** * Get Mint Digest * * The PoW must contain work that includes a recent * ethereum block hash (challenge hash) and the * msg.sender's address to prevent MITM attacks */ function getMintDigest( uint _challenge, address _minter, uint _nonce ) public pure returns (bytes32 digest) { /* Calculate digest. */ digest = keccak256(abi.encodePacked( _challenge, _minter, _nonce )); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /*************************************************************************** * * SETTERS * */ /** * Set Generations Per (Difficulty) Adjustment * * Token owner(s) can adjust the number of generations * per difficulty re-calculation. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function setGenPerAdjustment( address _token, uint _numBlocks ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _numBlocks); /* Return success. */ return true; } /** * Set (Fixed) Mint Amount */ function setMintFixed( address _token, uint _amount ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _amount); /* Return success. */ return true; } /** * Set (Dynamic) Mint Percentage */ function setMintPct( address _token, uint _pct ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _pct); /* Return success. */ return true; } /** * Set Token Parent(s) * * Enables the use of merged mining by specifying (parent) tokens * that offer an acceptibly HIGH difficulty for the child's own * mining challenge. * * Parents are saved in priority levels: * 1 - Most significant parent * 2 - 2nd most significant parent * ... * # - Least significant parent */ function setTokenParents( address _token, address[] _parents ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.parents' )); // FIXME How should we store a dynamic amount of parents? // Packed as bytes?? // FIXME TEMPORARILY LIMITED TO 3 bytes memory allParents = abi.encodePacked( _parents[0], _parents[1], _parents[2] ); /* Set value in Zer0net Db. */ _zer0netDb.setBytes(hash, allParents); /* Return success. */ return true; } /** * Set Token Provider */ function setTokenProvider( address _token, address _provider, bool _auth ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, _auth); /* Return success. */ return true; } /** * Set Mining Target */ function _setMiningTarget( address _token, uint _target ) private returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _target); /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * InfinityPool Interface * * Retrieves the current InfinityPool interface, * using the aname record from Zer0netDb. */ function _infinityPool() private view returns ( InfinityPoolInterface infinityPool ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitypool'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityPool = InfinityPoolInterface(aname); } /** * InfinityWell Interface * * Retrieves the current InfinityWell interface, * using the aname record from Zer0netDb. */ function _infinityWell() private view returns ( InfinityWellInterface infinityWell ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitywell'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityWell = InfinityWellInterface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } }
Set Generations Per (Difficulty) Adjustment Token owner(s) can adjust the number of generations per difficulty re-calculation. NOTE: This will help deter malicious miners from gaming the difficulty parameter, to the detriment of the token's community./
function setGenPerAdjustment( address _token, uint _numBlocks ) external onlyTokenProvider(_token) returns (bool success) { bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); _zer0netDb.setUint(hash, _numBlocks); return true;
902,650
./full_match/1/0x843F38142Df6C485dbc60f1DDD05599E3A7F2b4C/sources/contracts/Reward.sol
Returns the balance of USDT tokens owned by the caller. return The balance of USDT tokens./
function balanceOfUSDT() public view returns (uint256) { return usdtToken.balanceOf(address(this)); }
9,723,643
./full_match/80001/0xe33e889b24581E528Ae427eE765315CD9792E60b/sources/project_/contracts/ShopifyFactory.sol
Token being transferred _collectionId Id's of the collection _to destination account _id tokenId being tranferred _amount amount token being transferred/
function transferERC1155( uint256 _collectionId, address _to, uint256 _id, uint256 _amount, bytes calldata data ) external onlyRole(ADMIN_ROLE) { address _collection = collections[_collectionId]; require(_collection != address(0), "Collection hasn't deployed"); IShopify(IShopify(_collection)).safeTransferFrom( address(this), _to, _id, _amount, data ); }
9,464,476
./full_match/1287/0xF9e85c663448703bAc8DA3A81153065Dd8db42B7/sources/project_/contracts/treasury/TreasuryContract.sol
This function sets the symbol name as available, this function is called from records contract to reserve symbol for new version creation governanceSymbol Symbol for governance token communitySymbol Symbol for community token
function setSymbolsAsAvailable( string memory governanceSymbol, string memory communitySymbol ) external onlyRecordsVotingContract { treasuryCoreContract.setSymbolsAsAvailable( governanceSymbol, communitySymbol ); }
7,097,068
./partial_match/1313161554/0x964630b8327A6EB8730e3addcB8563d1e61b0100/sources/Comptroller.sol
Sets the collateralFactor for a market Admin function to set per-market collateralFactor chToken The market to set the factor on newCollateralFactorMantissa The new collateral factor, scaled by 1e18 return uint 0=success, otherwise a failure. (See ErrorReporter for details)/ Check caller is admin
function _setCollateralFactor( ChToken chToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(chToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } address(chToken) ]; if (currentLiquidationThreshold < newCollateralFactorMantissa) { liquidationThreshold[address(chToken)] = newCollateralFactorMantissa; emit NewLiquidationThreshold( address(chToken), currentLiquidationThreshold, newCollateralFactorMantissa ); } market.collateralFactorMantissa = newCollateralFactorMantissa; chToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); }
16,919,404
/** *Submitted for verification at Etherscan.io on 2019-08-23 */ /* Copyright 2017-2019 RigoBlock, Rigo Investment Sagl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.4; contract Pool { address public owner; /* * CONSTANT PUBLIC FUNCTIONS */ function balanceOf(address _who) external view returns (uint256); function totalSupply() external view returns (uint256 totaSupply); function getEventful() external view returns (address); function getData() external view returns (string memory name, string memory symbol, uint256 sellPrice, uint256 buyPrice); function calcSharePrice() external view returns (uint256); function getAdminData() external view returns (address, address feeCollector, address dragodAO, uint256 ratio, uint256 transactionFee, uint32 minPeriod); } contract ReentrancyGuard { // Locked state of mutex bool private locked = false; /// @dev Functions with this modifer cannot be reentered. The mutex will be locked /// before function execution and unlocked after. modifier nonReentrant() { // Ensure mutex is unlocked require( !locked, "REENTRANCY_ILLEGAL" ); // Lock mutex before function call locked = true; // Perform function call _; // Unlock mutex after function call locked = false; } } contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } interface ProofOfPerformanceFace { /* * CORE FUNCTIONS */ /// @dev Allows anyone to allocate the pop reward to pool wizards. /// @param _ofPool Number of pool id in registry. function claimPop(uint256 _ofPool) external; /// @dev Allows RigoBlock Dao to update the pools registry. /// @param _dragoRegistry Address of new registry. function setRegistry(address _dragoRegistry) external; /// @dev Allows RigoBlock Dao to update its address. /// @param _rigoblockDao Address of new dao. function setRigoblockDao(address _rigoblockDao) external; /// @dev Allows RigoBlock Dao to set the ratio between assets and performance reward for a group. /// @param _ofGroup Id of the pool. /// @param _ratio Id of the pool. /// @notice onlyRigoblockDao can set ratio. function setRatio(address _ofGroup, uint256 _ratio) external; /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Gets data of a pool. /// @param _ofPool Id of the pool. /// @return Bool the pool is active. /// @return address of the pool. /// @return address of the pool factory. /// @return price of the pool in wei. /// @return total supply of the pool in units. /// @return total value of the pool in wei. /// @return value of the reward factor or said pool. /// @return ratio of assets/performance reward (from 0 to 10000). /// @return value of the pop reward to be claimed in GRGs. function getPoolData(uint256 _ofPool) external view returns ( bool active, address thePoolAddress, address thePoolGroup, uint256 thePoolPrice, uint256 thePoolSupply, uint256 poolValue, uint256 epochReward, uint256 ratio, uint256 pop ); /// @dev Returns the highwatermark of a pool. /// @param _ofPool Id of the pool. /// @return Value of the all-time-high pool nav. function getHwm(uint256 _ofPool) external view returns (uint256); /// @dev Returns the reward factor for a pool. /// @param _ofPool Id of the pool. /// @return Value of the reward factor. function getEpochReward(uint256 _ofPool) external view returns (uint256); /// @dev Returns the split ratio of asset and performance reward. /// @param _ofPool Id of the pool. /// @return Value of the ratio from 1 to 100. function getRatio(uint256 _ofPool) external view returns (uint256); /// @dev Returns the proof of performance reward for a pool. /// @param _ofPool Id of the pool. /// @return popReward Value of the pop reward in Rigo tokens. /// @return performanceReward Split of the performance reward in Rigo tokens. /// @notice epoch reward should be big enough that it. /// @notice can be decreased if number of funds increases. /// @notice should be at least 10^6 (just as pool base) to start with. /// @notice rigo token has 10^18 decimals. function proofOfPerformance(uint256 _ofPool) external view returns (uint256 popReward, uint256 performanceReward); /// @dev Checks whether a pool is registered and active. /// @param _ofPool Id of the pool. /// @return Bool the pool is active. function isActive(uint256 _ofPool) external view returns (bool); /// @dev Returns the address and the group of a pool from its id. /// @param _ofPool Id of the pool. /// @return Address of the target pool. /// @return Address of the pool's group. function addressFromId(uint256 _ofPool) external view returns ( address pool, address group ); /// @dev Returns the price a pool from its id. /// @param _ofPool Id of the pool. /// @return Price of the pool in wei. /// @return Number of tokens of a pool (totalSupply). function getPoolPrice(uint256 _ofPool) external view returns ( uint256 thePoolPrice, uint256 totalTokens ); /// @dev Returns the address and the group of a pool from its id. /// @param _ofPool Id of the pool. /// @return Address of the target pool. /// @return Address of the pool's group. function calcPoolValue(uint256 _ofPool) external view returns ( uint256 aum ); } contract Inflation { uint256 public period; /* * CORE FUNCTIONS */ function mintInflation(address _thePool, uint256 _reward) external returns (bool); function setInflationFactor(address _group, uint256 _inflationFactor) external; function setMinimumRigo(uint256 _minimum) external; function setRigoblock(address _newRigoblock) external; function setAuthority(address _authority) external; function setProofOfPerformance(address _pop) external; function setPeriod(uint256 _newPeriod) external; /* * CONSTANT PUBLIC FUNCTIONS */ function canWithdraw(address _thePool) external view returns (bool); function timeUntilClaim(address _thePool) external view returns (uint256); function getInflationFactor(address _group) external view returns (uint256); } contract RigoToken { address public minter; uint256 public totalSupply; function balanceOf(address _who) external view returns (uint256); } interface DragoRegistry { //EVENTS event Registered(string name, string symbol, uint256 id, address indexed drago, address indexed owner, address indexed group); event Unregistered(string indexed name, string indexed symbol, uint256 indexed id); event MetaChanged(uint256 indexed id, bytes32 indexed key, bytes32 value); /* * CORE FUNCTIONS */ function register(address _drago, string calldata _name, string calldata _symbol, uint256 _dragoId, address _owner) external payable returns (bool); function unregister(uint256 _id) external; function setMeta(uint256 _id, bytes32 _key, bytes32 _value) external; function addGroup(address _group) external; function setFee(uint256 _fee) external; function updateOwner(uint256 _id) external; function updateOwners(uint256[] calldata _id) external; function upgrade(address _newAddress) external payable; //payable as there is a transfer of value, otherwise opcode might throw an error function setUpgraded(uint256 _version) external; function drain() external; /* * CONSTANT PUBLIC FUNCTIONS */ function dragoCount() external view returns (uint256); function fromId(uint256 _id) external view returns (address drago, string memory name, string memory symbol, uint256 dragoId, address owner, address group); function fromAddress(address _drago) external view returns (uint256 id, string memory name, string memory symbol, uint256 dragoId, address owner, address group); function fromName(string calldata _name) external view returns (uint256 id, address drago, string memory symbol, uint256 dragoId, address owner, address group); function getNameFromAddress(address _pool) external view returns (string memory); function getSymbolFromAddress(address _pool) external view returns (string memory); function meta(uint256 _id, bytes32 _key) external view returns (bytes32); function getGroups() external view returns (address[] memory); function getFee() external view returns (uint256); } /// @title Proof of Performance - Controls parameters of inflation. /// @author Gabriele Rigo - <gab@rigoblock.com> // solhint-disable-next-line contract ProofOfPerformance is SafeMath, ReentrancyGuard, ProofOfPerformanceFace { address public RIGOTOKENADDRESS; address public dragoRegistry; address public rigoblockDao; mapping (uint256 => PoolPrice) poolPrice; mapping (address => Group) groups; struct PoolPrice { uint256 highwatermark; } struct Group { uint256 rewardRatio; } modifier onlyRigoblockDao() { require( msg.sender == rigoblockDao, "ONLY_RIGOBLOCK_DAO" ); _; } constructor( address _rigoTokenAddress, address _rigoblockDao, address _dragoRegistry) public { RIGOTOKENADDRESS = _rigoTokenAddress; rigoblockDao = _rigoblockDao; dragoRegistry = _dragoRegistry; } /* * CORE FUNCTIONS */ /// @dev Allows anyone to allocate the pop reward to pool wizards. /// @param _ofPool Number of pool id in registry. function claimPop(uint256 _ofPool) external nonReentrant { DragoRegistry registry = DragoRegistry(dragoRegistry); address poolAddress; (poolAddress, , , , , ) = registry.fromId(_ofPool); (uint256 pop, ) = proofOfPerformanceInternal(_ofPool); require( pop > 0, "POP_REWARD_IS_NULL" ); uint256 price = Pool(poolAddress).calcSharePrice(); poolPrice[_ofPool].highwatermark = price; require( Inflation(getMinter()).mintInflation(poolAddress, pop), "MINT_INFLATION_ERROR" ); } /// @dev Allows RigoBlock Dao to update the pools registry. /// @param _dragoRegistry Address of new registry. function setRegistry(address _dragoRegistry) external onlyRigoblockDao { dragoRegistry = _dragoRegistry; } /// @dev Allows RigoBlock Dao to update its address. /// @param _rigoblockDao Address of new dao. function setRigoblockDao(address _rigoblockDao) external onlyRigoblockDao { rigoblockDao = _rigoblockDao; } /// @dev Allows RigoBlock Dao to set the ratio between assets and performance reward for a group. /// @param _ofGroup Id of the pool. /// @param _ratio Id of the pool. /// @notice onlyRigoblockDao can set ratio. function setRatio( address _ofGroup, uint256 _ratio) external onlyRigoblockDao { require( _ratio <= 10000, "RATIO_BIGGER_THAN_10000" ); //(from 0 to 10000) groups[_ofGroup].rewardRatio = _ratio; } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Gets data of a pool. /// @param _ofPool Id of the pool. /// @return Bool the pool is active. /// @return address of the pool. /// @return address of the pool factory. /// @return price of the pool in wei. /// @return total supply of the pool in units. /// @return total value of the pool in wei. /// @return value of the reward factor or said pool. /// @return ratio of assets/performance reward (from 0 to 10000). /// @return value of the pop reward to be claimed in GRGs. function getPoolData(uint256 _ofPool) external view returns ( bool active, address thePoolAddress, address thePoolGroup, uint256 thePoolPrice, uint256 thePoolSupply, uint256 poolValue, uint256 epochReward, uint256 ratio, uint256 pop ) { active = isActiveInternal(_ofPool); (thePoolAddress, thePoolGroup) = addressFromIdInternal(_ofPool); (thePoolPrice, thePoolSupply, poolValue) = getPoolPriceAndValueInternal(_ofPool); (epochReward, , ratio) = getInflationParameters(_ofPool); (pop, ) = proofOfPerformanceInternal(_ofPool); return( active, thePoolAddress, thePoolGroup, thePoolPrice, thePoolSupply, poolValue, epochReward, ratio, pop ); } /// @dev Returns the highwatermark of a pool. /// @param _ofPool Id of the pool. /// @return Value of the all-time-high pool nav. function getHwm(uint256 _ofPool) external view returns (uint256) { return poolPrice[_ofPool].highwatermark; } /// @dev Returns the reward factor for a pool. /// @param _ofPool Id of the pool. /// @return Value of the reward factor. function getEpochReward(uint256 _ofPool) external view returns (uint256) { (uint256 epochReward, , ) = getInflationParameters(_ofPool); return epochReward; } /// @dev Returns the split ratio of asset and performance reward. /// @param _ofPool Id of the pool. /// @return Value of the ratio from 1 to 100. function getRatio(uint256 _ofPool) external view returns (uint256) { ( , , uint256 ratio) = getInflationParameters(_ofPool); return ratio; } /// @dev Returns the proof of performance reward for a pool. /// @param _ofPool Id of the pool. /// @return popReward Value of the pop reward in Rigo tokens. /// @return performanceReward Split of the performance reward in Rigo tokens. /// @notice epoch reward should be big enough that it. /// @notice can be decreased if number of funds increases. /// @notice should be at least 10^6 (just as pool base) to start with. /// @notice rigo token has 10^18 decimals. function proofOfPerformance(uint256 _ofPool) external view returns (uint256 popReward, uint256 performanceReward) { return proofOfPerformanceInternal(_ofPool); } /// @dev Checks whether a pool is registered and active. /// @param _ofPool Id of the pool. /// @return Bool the pool is active. function isActive(uint256 _ofPool) external view returns (bool) { return isActiveInternal(_ofPool); } /// @dev Returns the address and the group of a pool from its id. /// @param _ofPool Id of the pool. /// @return Address of the target pool. /// @return Address of the pool's group. function addressFromId(uint256 _ofPool) external view returns ( address pool, address group ) { return (addressFromIdInternal(_ofPool)); } /// @dev Returns the price a pool from its id. /// @param _ofPool Id of the pool. /// @return Price of the pool in wei. /// @return Number of tokens of a pool (totalSupply). function getPoolPrice(uint256 _ofPool) external view returns ( uint256 thePoolPrice, uint256 totalTokens ) { (thePoolPrice, totalTokens, ) = getPoolPriceAndValueInternal(_ofPool); } /// @dev Returns the address and the group of a pool from its id. /// @param _ofPool Id of the pool. /// @return Address of the target pool. /// @return Address of the pool's group. function calcPoolValue(uint256 _ofPool) external view returns ( uint256 aum ) { ( , , aum) = getPoolPriceAndValueInternal(_ofPool); } /* * INTERNAL FUNCTIONS */ /// @dev Returns the split ratio of asset and performance reward. /// @param _ofPool Id of the pool. /// @return Value of the reward factor. /// @return Value of epoch time. /// @return Value of the ratio from 1 to 100. function getInflationParameters(uint256 _ofPool) internal view returns ( uint256 epochReward, uint256 epochTime, uint256 ratio ) { ( , address group) = addressFromIdInternal(_ofPool); epochReward = Inflation(getMinter()).getInflationFactor(group); epochTime = Inflation(getMinter()).period(); ratio = groups[group].rewardRatio; } /// @dev Returns the address of the Inflation contract. /// @return Address of the minter/inflation. function getMinter() internal view returns (address) { RigoToken token = RigoToken(RIGOTOKENADDRESS); return token.minter(); } /// @dev Returns the proof of performance reward for a pool. /// @param _ofPool Id of the pool. /// @return popReward Value of the pop reward in Rigo tokens. /// @return performanceReward Split of the performance reward in Rigo tokens. /// @notice epoch reward should be big enough that it can be decreased when number of funds increases /// @notice should be at least 10^6 (just as pool base) to start with. function proofOfPerformanceInternal(uint256 _ofPool) internal view returns (uint256 popReward, uint256 performanceReward) { uint256 highwatermark; if (poolPrice[_ofPool].highwatermark == 0) { highwatermark = 1 ether; } else { highwatermark = poolPrice[_ofPool].highwatermark; } (uint256 newPrice, uint256 tokenSupply, uint256 poolValue) = getPoolPriceAndValueInternal(_ofPool); require ( newPrice >= highwatermark, "PRICE_LOWER_THAN_HWM" ); (address thePoolAddress, ) = addressFromIdInternal(_ofPool); require( address(Pool(thePoolAddress)).balance <= poolValue && poolValue * 1 ether / address(Pool(thePoolAddress)).balance < 100 * 1 ether, "ETH_HIGHER_THAN_AUM_OR_ETH_AUM_RATIO_BELOW_1PERCENT_ERROR" ); (uint256 epochReward, uint256 epochTime, uint256 rewardRatio) = getInflationParameters(_ofPool); uint256 assetsComponent = safeMul( poolValue, epochReward ) * epochTime / 1 days; // proportional to epoch time uint256 performanceComponent = safeMul( safeMul( (newPrice - highwatermark), tokenSupply ) / 1000000, // Pool(thePoolAddress).BASE(), epochReward ) * 365 days / 1 days; uint256 assetsReward = safeMul( assetsComponent, safeSub(10000, rewardRatio) // 100000 = 100% ) / 10000 ether * address(Pool(thePoolAddress)).balance / poolValue; // reward inversly proportional to Eth in pool performanceReward = safeDiv( safeMul(performanceComponent, rewardRatio), 10000 ether * address(Pool(thePoolAddress)).balance / poolValue ) * 10; // rationalization by 2-20 rule popReward = safeAdd(performanceReward, assetsReward); if (popReward > RigoToken(RIGOTOKENADDRESS).totalSupply() / 10000) { popReward = RigoToken(RIGOTOKENADDRESS).totalSupply() / 10000; // max single reward 0.01% of total supply } } /// @dev Checks whether a pool is registered and active. /// @param _ofPool Id of the pool. /// @return Bool the pool is active. function isActiveInternal(uint256 _ofPool) internal view returns (bool) { DragoRegistry registry = DragoRegistry(dragoRegistry); (address thePool, , , , , ) = registry.fromId(_ofPool); if (thePool != address(0)) { return true; } } /// @dev Returns the address and the group of a pool from its id. /// @param _ofPool Id of the pool. /// @return Address of the target pool. /// @return Address of the pool's group. function addressFromIdInternal(uint256 _ofPool) internal view returns ( address pool, address group ) { DragoRegistry registry = DragoRegistry(dragoRegistry); (pool, , , , , group) = registry.fromId(_ofPool); return (pool, group); } /// @dev Returns price, supply, aum and boolean of a pool from its id. /// @param _ofPool Id of the pool. /// @return Price of the pool in wei. /// @return Number of tokens of a pool (totalSupply). /// @return Address of the target pool. /// @return Address of the pool's group. function getPoolPriceAndValueInternal(uint256 _ofPool) internal view returns ( uint256 thePoolPrice, uint256 totalTokens, uint256 aum ) { (address poolAddress, ) = addressFromIdInternal(_ofPool); Pool pool = Pool(poolAddress); thePoolPrice = pool.calcSharePrice(); totalTokens = pool.totalSupply(); require( thePoolPrice != 0 && totalTokens !=0, "POOL_PRICE_OR_TOTAL_SUPPLY_NULL_ERROR" ); aum = thePoolPrice * totalTokens / 1000000; // pool.BASE(); } }
INTERNAL FUNCTIONS/ Returns the split ratio of asset and performance reward. _ofPool Id of the pool. return Value of the reward factor. return Value of epoch time. return Value of the ratio from 1 to 100.
function getInflationParameters(uint256 _ofPool) internal view returns ( uint256 epochReward, uint256 epochTime, uint256 ratio ) { ( , address group) = addressFromIdInternal(_ofPool); epochReward = Inflation(getMinter()).getInflationFactor(group); epochTime = Inflation(getMinter()).period(); ratio = groups[group].rewardRatio; }
5,417,762
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.8.4 <0.9.0; pragma abicoder v2; import '@openzeppelin/contracts/utils/Address.sol'; import './Verifier.sol'; import './Bytes.sol'; import './RegistryUser.sol'; /** * Oracle Proxy * Name: Oracle * Domain: DKDAO, * */ contract OracleProxy is RegistryUser { // Verify signature using Bytes for bytes; // Verify signature using Verifier for bytes; // Use address lib for address using Address for address; // Controller list mapping(address => bool) private _controllers; // List controller event ListAddress(address indexed addr); // Delist controller event DelistAddress(address indexed addr); constructor(address registry_, bytes32 domain_) { // Set the operator _registryUserInit(registry_, domain_); } // Only allow listed oracle to trigger oracle proxy modifier onlyListedController(bytes memory proof) { require(proof.length == 97, 'Swap: Wrong size of the proof, it must be 97 bytes'); bytes memory signature = proof.readBytes(0, 65); bytes memory message = proof.readBytes(65, 32); address sender = message.verifySerialized(signature); uint256 timeAndNonce = message.readUint256(0); uint256 expired = timeAndNonce >> 128; require(expired > block.timestamp, 'OracleProxy: This proof was expired'); require(_controllers[sender], 'OracleProxy: Controller was not in the list'); _; } /******************************************************* * Operator section ********************************************************/ // Add real Oracle to controller list function addController(address controllerAddr) external onlyAllowSameDomain('Operator') returns (bool) { _controllers[controllerAddr] = true; emit ListAddress(controllerAddr); return true; } // Remove real Oracle from controller list function removeController(address controllerAddr) external onlyAllowSameDomain('Operator') returns (bool) { _controllers[controllerAddr] = false; emit DelistAddress(controllerAddr); return true; } /******************************************************* * Public section ********************************************************/ // Safe call to a target address with given payload function safeCall( bytes memory proof, address target, uint256 value, bytes memory data ) external onlyListedController(proof) returns (bool) { target.functionCallWithValue(data, value); return true; } // Delegatecall to a target address with given payload function safeDelegateCall( bytes memory proof, address target, bytes calldata data ) external onlyListedController(proof) returns (bool) { target.functionDelegateCall(data); return true; } /******************************************************* * View section ********************************************************/ // Get valid nonce of next transaction function getValidTimeNonce(uint256 timeout, uint256 randomNonce) external view returns (uint256) { return ((block.timestamp + timeout) << 128) | randomNonce; } // Check a address is controller function isController(address inputAddress) external view returns (bool) { return _controllers[inputAddress]; } }
Check a address is controller
function isController(address inputAddress) external view returns (bool) { return _controllers[inputAddress]; }
13,043,562
./partial_match/97/0xBE2870d1dE8c30D31388fb1e86c209d85f0e8866/sources/AnimalFactory.sol
function to set the new price can only be called from owner wallet/
function setPriceRate(uint newPrice) public onlyOwner returns (bool) { uint convertedpricetoEther = newPrice; weiPerAnimal = convertedpricetoEther; }
11,369,250
// contracts/CryptoshackStaking.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; interface ICryptoshackContract { function balanceOf(address owner) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); } interface IWorldTokenContract { function transferFrom(address from, address to, uint256 tokenId) external; } contract CryptoshackStaking { // contract owner address public owner; // reward token contract ICryptoshackContract worldTokenContract; // staking token contract IWorldTokenContract cryptoshackContract; // is staking allowed or not bool public stakingAllowed; bool public emergencyMode; uint public undistributed; // total reward tokens claimed uint public totalClaimed; // general info by token type uint[3][5] typeToNumbers; // token Id to staker mapping(uint => address) idToStaker; // staker to all staked tokens IDs mapping(address => uint[]) stakerToIds; // token ID to it's index in stakerToIds mapping(uint => uint) tokenIdToStakerIndex; // token ID to reward tokens claimed mapping(uint => uint) tokenToClaimed; constructor() { owner=msg.sender; // staked | allocation percent | reward accumulated typeToNumbers[0]=[0,50,0]; typeToNumbers[1]=[0,50,0]; typeToNumbers[2]=[0,30,0]; typeToNumbers[3]=[0,20,0]; typeToNumbers[4]=[0,20,0]; } // stake tokens function stake(uint[] calldata tokenIds) external onlyStakingAllowed noContracts { uint tokenId; uint tokenType; for (uint i;i<tokenIds.length;i++) { tokenId=tokenIds[i]; tokenType=tokenId/10000; // increase staked tokens of a type amount typeToNumbers[tokenType][0]++; // set claimed level to the current reward tokenToClaimed[tokenId]=typeToNumbers[tokenType][2]; // set staker idToStaker[tokenId]=msg.sender; // set idex of token in staker's wallet tokenIdToStakerIndex[tokenId]=stakerToIds[msg.sender].length; // push the token to staker's wallet stakerToIds[msg.sender].push(tokenId); // move the CS token to the contract cryptoshackContract.transferFrom(msg.sender, address(this), tokenId); } } // claim and unstake if `unstake` is true function claim(uint[] calldata tokenIds, bool unstake) external noContracts { uint[] storage tokensArray; uint totalClaimable; uint tokenType; uint tokenId; uint lastIndex; uint tokenIndex; for (uint i;i<tokenIds.length;i++) { tokenId=tokenIds[i]; require(idToStaker[tokenId]==msg.sender, "You're not the staker"); tokenType=tokenId/10000; totalClaimable+=typeToNumbers[tokenType][2]-tokenToClaimed[tokenId]; tokenToClaimed[tokenId]=typeToNumbers[tokenType][2]; if (unstake) { tokensArray=stakerToIds[msg.sender]; lastIndex=tokensArray.length-1; tokenIndex=tokenIdToStakerIndex[tokenId]; //nullify the staker address idToStaker[tokenId]=address(0); //update staked of a type amount typeToNumbers[tokenType][0]--; //swap token to be removed with the last one tokensArray[tokenIndex]=tokensArray[lastIndex]; //update swapped token index tokenIdToStakerIndex[tokensArray[lastIndex]]=tokenIndex; //remove last element tokensArray.pop(); //move token back to the staker wallet cryptoshackContract.transferFrom(address(this), msg.sender, tokenId); } } if (totalClaimable > 0) { totalClaimed+=totalClaimable; worldTokenContract.transfer(msg.sender, totalClaimable); } } // get claimable amount of reward tokens function getClaimable(uint[] calldata tokenIds) external view returns(uint) { uint totalClaimable; for (uint i;i<tokenIds.length;i++) { if (idToStaker[tokenIds[i]]!=address(0)) { totalClaimable+=typeToNumbers[tokenIds[i]/10000][2]-tokenToClaimed[tokenIds[i]]; } } return totalClaimable; } // get claimable amount for the wallet function getClaimableByWallet(address wallet) external view returns(uint) { uint totalClaimable; for (uint i;i<stakerToIds[wallet].length;i++) { if (idToStaker[stakerToIds[wallet][i]]!=address(0)) { totalClaimable+=typeToNumbers[stakerToIds[wallet][i]/10000][2]-tokenToClaimed[stakerToIds[wallet][i]]; } } return totalClaimable; } // get staker wallet of token Id function getStaker(uint tokenId) external view returns(address) { return idToStaker[tokenId]; } // get total tokens staked function stakedTotal() external view returns(uint) { uint totalStaked; for (uint8 i;i<5;i++) { totalStaked+=typeToNumbers[i][0]; } return totalStaked; } // get all tokens staked by wallet function stakedByWallet(address wallet) external view returns(uint[] memory) { return stakerToIds[wallet]; } // returns the count of the staked tokens of a type function getStakedOfType(uint tokenType) external view returns(uint) { return typeToNumbers[tokenType][0]; } // top up the balance and distribute the reward token function topUp(uint amount) external onlyOwner { // distributing amount + remains from the previous topUp uint todistribute=amount+undistributed; // total amount of gophers + golden gophers staked uint gophersStaked=(typeToNumbers[0][0]+typeToNumbers[1][0]); // total amount of members + lege staked uint membersStaked=(typeToNumbers[3][0]+typeToNumbers[4][0]); // total amount that will be distributed uint totalShare; if (gophersStaked > 0) { // share per gopher or golden gopher uint gophersShare=(todistribute*typeToNumbers[0][1]/100)/(gophersStaked); typeToNumbers[0][2]+=gophersShare; typeToNumbers[1][2]+=gophersShare; totalShare+=gophersShare*gophersStaked; } if (membersStaked > 0) { // share per member or lege uint membersShare=(todistribute*typeToNumbers[4][1]/100)/(membersStaked); typeToNumbers[3][2]+=membersShare; typeToNumbers[4][2]+=membersShare; totalShare+=membersShare*membersStaked; } if (typeToNumbers[2][0] > 0) { // share per caddie uint caddiesShare=(todistribute*typeToNumbers[2][1]/100)/(typeToNumbers[2][0]); typeToNumbers[2][2]+=caddiesShare; totalShare+=caddiesShare*typeToNumbers[2][0]; } // storing the not distributed amount for the next time undistributed=todistribute-totalShare; worldTokenContract.transferFrom(msg.sender, address(this), amount); } // allow owner to remove token from stake in case of problems with contract function ejectStakingTokens(address wallet, uint tokenId) external onlyOwner onlyEmergency { cryptoshackContract.transferFrom(address(this), wallet, tokenId); } // allow owner to remove WRLD tokens from the contract in case of a problems function ejectRewardTokens(address wallet) external onlyOwner onlyEmergency { worldTokenContract.transfer(wallet, worldTokenContract.balanceOf(address(this))); } // set reward token contract function setWorldTokenContract(address worldTokenContract_) external onlyOwner { worldTokenContract=ICryptoshackContract(worldTokenContract_); } // set staking token contract function setCryptoshackContract(address cryptoshackContract_) external onlyOwner { cryptoshackContract=IWorldTokenContract(cryptoshackContract_); } // switch the stakingAllowed flag function switchStakingAllowed() external onlyOwner { stakingAllowed=!stakingAllowed; } // switch the stakingAllowed flag function switchEmergencyMode() external onlyOwner { emergencyMode=!emergencyMode; } // transfer ownership function transferOwnership(address newOwner) external onlyOwner { owner=newOwner; } // execute only if stakingAllowed modifier onlyStakingAllowed { require(stakingAllowed,"Staking is not allowed!"); _; } // execute only if emergency mode activated modifier onlyEmergency { require(emergencyMode, "Emergency mode off"); _; } // execute only if caller is not a contract modifier noContracts { require(msg.sender == tx.origin, "No contracts allowed!"); _; } // execute only if caller is an owner modifier onlyOwner { require(msg.sender == owner); _; } }
get staker wallet of token Id
function getStaker(uint tokenId) external view returns(address) { return idToStaker[tokenId]; }
15,134,793
./full_match/1/0x533C5c15E073f56860B3091d7f7414f1cf6d4aE3/sources/contracts/RWAHubInstantMints.sol
Set the mintLimit constraint inside the TimeBasedRateLimiter base contract newMintLimit New limit that dictates how much RWA can be minted in a specified duration (in 18 decimals per the RWA contract)/
function setInstantMintLimit( uint256 newMintLimit ) external onlyRole(MANAGER_ADMIN) { _setInstantMintLimit(newMintLimit); }
3,221,142
// SPDX-License-Identifier: MIT // this contract is deployed on Kovan at 0xB5600D46f8e7191B3791eCCEC7697a537976d4d5 pragma solidity ^0.6.6; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/ILendingPoolAddressesProviderV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract BrightLink is ChainlinkClient { bool public paused; int Id = 0; uint16 private constant referral = 0; uint16 index; uint256 aggregateData; uint16 w1 = 100; uint16 w2 = 100; uint16 w3 = 100; uint16 minResponses = 2; uint16 badOracles = 0; bytes32 private immutable jobID; uint256 private immutable fee; address private immutable oracle; uint256 public depositedFunds; uint256[3] public oracleData; uint256 public value; address private owner; address public dai_address; address public adai_address; address public poolAddress; address public poolAddressProvider; string[3] public APIaddresses; mapping(address => int) private customerToAgreementID; mapping(address => int) private donorToAgreementID; mapping(int => address) private agreementIdToDonor; mapping(int => uint256) private agreementIdToBaseline; mapping(int => uint256) private agreementIdToValue; mapping (int => uint256) public agreementIdToRetrievedData; IERC20 public immutable dai; IERC20 public immutable adai; ILendingPoolV2 public lendingPool; ILendingPoolAddressesProviderV2 public provider; constructor(address _dai_address, address _adai_address, address _link, address _poolAddressProvider, address _oracle, string memory _jobID, uint256 _fee) public{ // var instantiations owner = msg.sender; paused = false; depositedFunds = 0; dai_address = _dai_address; adai_address = _adai_address; poolAddressProvider = _poolAddressProvider; dai = IERC20(dai_address); adai = IERC20(adai_address); provider = ILendingPoolAddressesProviderV2(poolAddressProvider); poolAddress = provider.getLendingPool(); lendingPool = ILendingPoolV2(poolAddress); oracle = _oracle; jobID = stringToBytes32(_jobID); fee = _fee; APIaddresses[0] = "https://raw.githubusercontent.com/jmcook1186/jmcook1186.github.io/main/Data/BrightLinkData/SentinelData.json"; APIaddresses[1] = "https://raw.githubusercontent.com/jmcook1186/jmcook1186.github.io/main/Data/BrightLinkData/LandsatData.json"; APIaddresses[2] = "https://raw.githubusercontent.com/jmcook1186/jmcook1186.github.io/main/Data/BrightLinkData/ModisData.json"; oracleData[0] = 0; oracleData[1] = 0; oracleData[2] = 0; // set link token address depending on network if (_link == address(0)) { setPublicChainlinkToken(); } else { setChainlinkToken(_link); } } /** @dev Add new customer to contract. Adds customer to mappings, generates new agreementId. Triggers deposit of funds to Aave pool to begin accruing yield. Adds value to cumulative deposits. Requires remote sensing scripts to have been run to estabish baseline data at API endpoints Requires donor to approve dai transfer before function is called: dai.approve(contract,200e18,{'from':donor}) Approving _value only (rather than unlimited approval) protects against any re-entrancy attack. Removed onlyOwner modifier so anyone can add an agreement if paid for by a donor. Requires donor to have approved a DAI transfer of value >= _value. */ function addNewCustomer(address _customer, address _donor, uint256 _value) public notPaused { // require that the customer does not have an existing agreement require(customerToAgreementID[_customer] <= 0,"customer already exists"); depositedFunds += _value; customerToAgreementID[_customer] = Id; donorToAgreementID[_donor] = Id; agreementIdToValue[Id] = _value; agreementIdToDonor[Id] = _donor; require(dai.transferFrom(_donor, address(this), _value)); depositFundsToAave(); Id+=1; } /** @dev internal func called by addNewCustomer() sends all dai in contract to Aave lending pool, returning aDai */ function depositFundsToAave() internal{ dai.approve(poolAddress,1000000e18); dai.approve(address(this),1000000e18); lendingPool.deposit(dai_address, dai.balanceOf(address(this)), address(this), referral); } /** @dev returns accumulated aDai to Aave pool, retrieving Dai at 1:1 */ function WithdrawFundsFromAave(uint _amount) internal{ adai.approve(poolAddress, _amount); adai.approve(address(this), _amount); lendingPool.withdraw(dai_address, _amount, address(this)); } /** @dev internal, called by setBaseLine() and UpdateOracleData() sets weighting for aggregating the oracle data default is to trust all oracles equally (100,100,100) */ function setWeights(uint16 _w1, uint16 _w2, uint16 _w3) internal { w1 = _w1; w2 = _w2; w3 = _w3; } /** @dev assumes remote sensing scripts have been run setting baseline data at the API endpoints */ function setBaseLine(address _customer) public notPaused{ int id = customerToAgreementID[_customer]; // MOCKING: REPLACE NECT TWO LINES WITH HARD-CODED VALUE // requestDataFromAPI(); // validateOracleData(); aggregateData = 5; agreementIdToBaseline[id] = aggregateData; } /** @dev assumes remote sensing scripts have been run a second time, updating the API endpoints */ function UpdateOracleData(address _customer) public notPaused{ int id = customerToAgreementID[_customer]; requestDataFromAPI(); validateOracleData(); agreementIdToRetrievedData[id] = aggregateData; } /** @dev settles the agreement for a given customer by checking the agreed value and paying it to the customer's wallet if the updated values exceeds the baseline. Otherwise, return to donor. */ function settleAgreement(address _customer) public notPaused { // get ID from customer address int agreementId = customerToAgreementID[_customer]; uint256 amount = agreementIdToValue[agreementId]; uint256 threshold = agreementIdToBaseline[agreementId]; address donor = agreementIdToDonor[agreementId]; uint256 retrieval = agreementIdToRetrievedData[agreementId]; WithdrawFundsFromAave(amount); // subtract expended amount from the running total of deposits depositedFunds-= agreementIdToValue[agreementId]; // set transaction value to 0 to prevent re-spending agreementIdToValue[agreementId] = 0; customerToAgreementID[_customer] = 0; if (retrieval > threshold){ require(dai.transfer(_customer, amount)); } else{ require(dai.transfer(donor, amount)); } } /** @dev withdraws enough dai from Aave pool to equal the total accumulated profit and transfers it to the owners wallet always persists enough adai in contract to payout all active agreements */ function takeProfits() public onlyOwner { uint totalAmount = adai.balanceOf(address(this)); uint profit = totalAmount - depositedFunds; if (dai.balanceOf(address(this)) < profit){ WithdrawFundsFromAave(profit-dai.balanceOf(address(this))); } require(dai.transfer(owner, profit)); } /** @dev release any spare LINK to the contract owner */ function retrieveLINK() public onlyOwner{ LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(owner, link.balanceOf(address(this))), "Unable to transfer"); } function circuitBreaker(bool _paused) public onlyOwner{ paused = _paused; } function escapeHatch() public onlyOwner{ // for testing purposes, if all gone wrong, retrieve funds // to save having to get more from faucets if (dai.balanceOf(address(this))>0){ require(dai.transfer(owner,dai.balanceOf(address(this)))); } if (adai.balanceOf(address(this))>0){ require(adai.transfer(owner,adai.balanceOf(address(this)))); } LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); if (link.balanceOf(address(this))>0){ require(link.transfer(owner, link.balanceOf(address(this))), "Unable to transfer"); } } //////////////////////////// // INTERNAL ORACLE REQUEST FUNCS /** @dev outer function that calls the oracleRequest func once per oracle */ function requestDataFromAPI() internal onlyOwner notPaused{ // require protects against aggregaData ==0 from forgetting to set weights require(w1+w2+w3 != 0, "please set weights for aggregating oracle data"); index = 0; oracleRequest(APIaddresses[0]); oracleRequest(APIaddresses[1]); oracleRequest(APIaddresses[2]); } /** @dev This function calls the oracles by building the request then calling the internal fulfill() function. Each fulfill adds new data to the oracleData[] array and increments the index. */ function oracleRequest(string memory url) internal notPaused returns (bytes32 requestId) { // oracle request happens here. URL is passed as var url // args are jobID, callback address (this contract) and fulfill function from this contract Chainlink.Request memory request = buildChainlinkRequest(jobID, address(this), this.fulfill.selector); // Set the URL to perform the GET request on request.add("get", url); request.add("path", "data.0.number"); // Sends the request return sendChainlinkRequestTo(oracle, request, fee); } function fulfill(bytes32 _requestId, uint _value) public recordChainlinkFulfillment(_requestId){ // fulfill will be called 3x: 1x for each call to OracleRequest (via this.fulfill.selector arg) // assign data from oracle to position in oracleData array oracleData[index] = _value; // iterate through array indexes index = index+1; // increment index // calculate weighted mean of data in oracleData array aggregateData = ((w1*oracleData[0]/100)+(w2*oracleData[1]/100)+(w3*oracleData[2]/100))/3; } /** @dev ensures a sufficient number of oracles return valid data avoids accidentally centralizing workflow by relying on 1 oracle */ function validateOracleData() internal notPaused { for (uint16 i = 0; i<oracleData.length; i++) { //for loop example if (oracleData[i] ==0){ badOracles++; } } } // VIEW FUNCS function viewValueFromOracle() public view returns(uint256 viewValue){ // show aggregated oracle data to user viewValue = aggregateData; } function checkIdForCustomer(address _customer) public view returns(int){ return(customerToAgreementID[_customer]); } function checkIdForDonor(address _donor) public view returns(int){ return(donorToAgreementID[_donor]); } function checkvalueForAgreementId(int agreementId) public view returns(uint256){ return(agreementIdToValue[agreementId]); } function checkDepositAmount() public view returns(uint256 deposit){ // view function to show user how much DAI was deposited deposit = depositedFunds; } function checkBalance() public view returns (uint256 dai_balance, uint256 adai_balance) { // balance of DAI and aDAI in contract // aDAI is the debt token from the Aave pool dai_balance = dai.balanceOf(address(this)); adai_balance = adai.balanceOf(address(this)); } // MODIFIERS AND ACCESSORY FUNCTIONS modifier onlyOwner(){ require(owner==msg.sender); _; } modifier notPaused(){ require(paused==false, "Contract is paused"); _; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } }
fulfill will be called 3x: 1x for each call to OracleRequest (via this.fulfill.selector arg) assign data from oracle to position in oracleData array iterate through array indexes calculate weighted mean of data in oracleData array
function fulfill(bytes32 _requestId, uint _value) public recordChainlinkFulfillment(_requestId){ oracleData[index] = _value; aggregateData = ((w1*oracleData[0]/100)+(w2*oracleData[1]/100)+(w3*oracleData[2]/100))/3; } ensures a sufficient number of oracles return valid data avoids accidentally centralizing workflow by relying on 1 oracle
1,045,965
// Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol@v4.5.2 // 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); } // File @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol@v4.5.2 // 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); } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol@v4.5.2 // 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 IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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-upgradeable/utils/AddressUpgradeable.sol@v4.5.2 // 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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)); } } // File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v4.5.2 // 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 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; } // File @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol@v4.5.2 // 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); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol@v4.5.2 // 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 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; } // File @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol@v4.5.2 // 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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} /** * @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[44] private __gap; } // File @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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; } // File @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol@v4.5.2 // 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 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; } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /** * @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; } // File @openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // File @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @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-upgradeable/utils/StorageSlotUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @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 StorageSlotUpgradeable { 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-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; /** * @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 ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // 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 StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.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) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @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 StorageSlotUpgradeable.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"); StorageSlotUpgradeable.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 StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.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) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @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; } // File @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; /** * @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 Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @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 Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(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); _upgradeToAndCallUUPS(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; /** * @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; } // File @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol@v4.5.2 // 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; } } // File @openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File contracts/metasimpz.sol pragma solidity ^0.8.4; // MMMMMMMMMO.,KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM0'.dWMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMNc.dWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMKl,;xNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMWx.'0MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWMMWKl.;0WMMMMMMMMMMMMMMMMMMM // MMMMMMMMKl.;kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx.;KMWMMMMMMMMMMMMMMMMM // MMMMMMWO,.dNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWc.dMMMMMMMMMMMMMMMMMMM // MMMMMM0'.kWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMd lWMMMMMMMMMMMMMMMMMM // MMMMMNc.dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN:.xMMMMMMMMMMMMMMMMMMM // MMMMM0',KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXl.lNMMMMMMMMMMMMMMMMMMM // MMMMMK,,KMWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMMMMMMMMMMMWd.:XMMMMMMMMMMMMMMMMMMMM // MMMMMNc.dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWWWMMMMMMMMMNl'xWMMMMMMMMMMMMMMMMMMM // MMMMMMK:.lKWWMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWKKWWMMMMMMMMMMNc'dkkkOKWMMMMMMMMMMMMM // MMMMMMMNd;'c0MMMMMMMMMMMMMMMMMW0xddddxOKNKd;;cx0XWWNKKNWKd::odxddood0WMMMMMMMMMM // MMMMMMMMWx.;KMMMMMMMMMMMMNOxOdlodkO0Oxdlc''xOo;;:::;,'cocdKWWWMMMMXxcoXMMMMMMMMM // MMMMMMMMk.;KMMMMMMMMMMMMMWO,.oKWMMMMMMWNXk:lOOxoc::cdo.,0WWMMMMMMMMMXclXMMMMMMMM // MMMMMMMNc.xMMMMMMMMMMMMWWNk;oWMMMMMMMMMMMM0:,:cllllcc;.dWWMMMMMMMMMMMO;xMMMMMMMM // MMMMMMMX;.OMWMMMWXOkdooodd,,0MMMMMMMMMMMMMWo.;ccokKKKo,xWMMMMMMMMMMMWO;xMMMMMMMM // MMMMMMMWl.oWMMMXdoodxO0XNWx;kMMMMMMMMMMMWMNl'lc..;o0K0::KMMMMMMMMMMMNlcXMMMMMMMM // MMMMMMMMK;.oXMMWNWXOxddx0NX:;KMWWMMMMMMMMNd.'c;.lOk0KKOl:kNMWWMMMMNOclKMMMMMMMMM // MMMMMMMMMXo,,o0WXdcldddlclc,,cd0NMMWMWXkd:.;ool,,x0KK0K0:.:odkOkxdolkNMMMMMMMMMM // MMMMMMMMMMMXo.cKl:OKkdx0Kxcd0klllooooolll''x000k':0KKKKKc.o0xdddxOXWMMMMMMMMMMMM // MMMMMMMMMMMMd.lk;dKKOl;cOKKKKKKK0kxxkO0KKx,;ooo:'o0KKKKKc.kMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMx.ck:dK00Oock0xkKKKKKK00KKKKKKOoccclx0K0KKK0:,0MMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMX:'xd;x0xodOOc:k0KKKKKK0KKK00KKKKKK0KK0KK0Kk,cNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMKc'ldol:;:lc'lK00KKKKK0KKKKKKKKKKK0KKK0KKKl'kWMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMNkc;loodx0Xd;d0KKKK00KKKKKKKKKKKKKKKK0K0o,dWWMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMWKxllllloo:;lkKK000KKKKKKKKKKKKKK0KKOc;xNMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMWMMMWWXKXXN0c,cx0KK00KK0KKKKKKKKK0kc';0WMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMWKxl;,;'.,cloxO0KKKK0KK0kdlc;...:kNMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMNk:;:''xXXo;c:'':oollllll:,,cl;oOk;.;OWMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMWWWO;,lkKx:okx:.,dko:cc:cc;cc:odl'.dKKl,,'oXMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMXo':kKKKKOdloo;cKN0,.oXNNk,.cNMX;'llllk0o':KMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMXc.l0KK0K0KK0KKkolollccdxxo:clldllxOxoccd0d':KMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMNl.l0KKKK0Kk:,::ccloooo:,',;cll:;:cllldxl,,do'lNMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMWWd.:0KKKKK0Ko,dOxxdoolllllllloodxkO0XWMMMWXc.c:,OMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMWk.;OKK00KKKKc;KMMMMMMMMMMMMMMMMMMMMMMMWMMWMNl.:'cWMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMK,'xKK00KK0K0;:NMMMMMMMMMMMMMMMMMMMMMMMMMMMMM0,',,OMMMMMMMMMMMMMMMM // MMMMMMMMMMMMWl.l0KKKKKK0Kk,lWMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX;':.oMMMMMMMMMMMMMMMM // MMMMMMMMMMMMk.;OKK0KKKK0Kx.oMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx.:x'cNMMMMMMMMMMMMMMM // MMMMMMMMMMMX:.dK0KKKKKK0Ko.dMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx.;OO,;XMMMMMMMMMMMMMMM // MMMMMMMMMMMk.;OKKKKKKKKKKl.xMMMMMMMMMMMMMMMMMMMMMMMMMMMMWc.xXO,,KMMMMMMMMMMMMMMM contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract MetaSimpz is Initializable, ERC721Upgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; address proxyRegistryAddress; address[] public teamWallets; uint256[] public teamAllocation; uint256 totalSupply; uint256 basePrice; bytes32 merkleRoot; bool _pwMint; bool _publicMint; CountersUpgradeable.Counter private _tokenIdCounter; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() public initializer { __ERC721_init("MetaSimpz", "SIMPZ"); __Pausable_init(); __Ownable_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; proxyRegistryAddress = _proxyRegistryAddress; basePrice = 30000000000000000; totalSupply = 10000; _tokenIdCounter.increment(); teamAllocation = [15, 180, 225, 175, 175, 100, 130]; } function pwMint( uint256 count, bytes32[] calldata proof, string memory password ) public payable { require(_pwMint == true, "MINTING NOT YET STARTED"); bytes32 leaf = keccak256(abi.encodePacked(password)); require( MerkleProofUpgradeable.verify(proof, merkleRoot, leaf), "D'OH, WRONG PASSWORD" ); require(msg.value >= basePrice * count, "INCREASE PAYMENT TO MINT"); for (uint256 i = 0; i < count; i++) { uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= totalSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } } function ultiMint(uint256 count) public payable { require(_publicMint == true, "MINTING NOT YET STARTED"); require(msg.value >= basePrice * count, "INCREASE PAYMENT TO MINT"); for (uint256 i = 0; i < count; i++) { uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= totalSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } } function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function commencePasswordMint() public onlyOwner { _pwMint = true; } function commencePublicMint() public onlyOwner { _publicMint = true; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function NFTcount() public view returns (uint256) { uint256 currentNFT = _tokenIdCounter.current(); return currentNFT; } function _baseURI() internal pure override returns (string memory) { return "https://api.metasimpz.io/v1/metadata/"; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} // Team payouts function setTeamWallets(address[] calldata addresses) public onlyOwner { teamWallets = addresses; } function teamWithdraw() public onlyOwner { uint256 i = 0; uint256 _balance = address(this).balance; for (i = 0; i <= 5; i++) { uint256 cashOut = (_balance * teamAllocation[i]) / 1000; address payee = teamWallets[i]; (bool sent, bytes memory data) = payee.call{value: cashOut}(""); require(sent, "Failed to send Ether"); } uint256 finalAllocation = address(this).balance; address lastWallet = teamWallets[6]; (bool s, bytes memory d) = lastWallet.call{value: finalAllocation}(""); require(s, "Failed to send Ether"); } function withdrawBackup() public onlyOwner { uint256 amount = address(this).balance; require(payable(owner()).send(amount)); } }
ERC721 token receiver interface Interface for any contract that wants to support safeTransfers from ERC721 asset contracts./
interface IERC721ReceiverUpgradeable { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } }
16,192
./full_match/1/0xd7Cc88bB603DceAFB5E8290d8188C8BF36fD742B/sources/home/konstantinovv/source/pollen/investment-fund-dao/contracts/StakeholdersWallet.sol
Update wallet address of a stakeholder (only the stakeholder may call)
function updateWallet(uint stakeholderID, address newWallet) external { require(stakeholders[stakeholderID].wallet == msg.sender, "unauthorized"); _revertZeroAddress(newWallet); stakeholders[stakeholderID].wallet = newWallet; emit WalletUpdate(stakeholderID, newWallet); }
8,310,108
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IWnDGame.sol"; import "./interfaces/ITower.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/IGP.sol"; import "./interfaces/IWnD.sol"; import "./interfaces/ISacrificialAlter.sol"; import "./interfaces/IRandomizer.sol"; contract WnDGameCR is IWnDGame, Ownable, ReentrancyGuard, Pausable { event MintCommitted(address indexed owner, uint256 indexed amount); event MintRevealed(address indexed owner, uint256 indexed amount); struct MintCommit { bool stake; uint16 amount; } uint256 public treasureChestTypeId; // max $GP cost uint256 private maxGpCost = 72000 ether; // address -> commit # -> commits mapping(address => mapping(uint16 => MintCommit)) private _mintCommits; // address -> commit num of commit need revealed for account mapping(address => uint16) private _pendingCommitId; // commit # -> offchain random mapping(uint16 => uint256) private _commitRandoms; uint16 private _commitId = 1; uint16 private pendingMintAmt; bool public allowCommits = true; // address => can call addCommitRandom mapping(address => bool) private admins; // reference to the Tower for choosing random Dragon thieves ITower public tower; // reference to $GP for burning on mint IGP public gpToken; // reference to Traits ITraits public traits; // reference to NFT collection IWnD public wndNFT; // reference to alter collection ISacrificialAlter public alter; constructor() { _pause(); } /** CRITICAL TO SETUP */ modifier requireContractsSet() { require(address(gpToken) != address(0) && address(traits) != address(0) && address(wndNFT) != address(0) && address(tower) != address(0) && address(alter) != address(0) , "Contracts not set"); _; } function setContracts(address _gp, address _traits, address _wnd, address _tower, address _alter) external onlyOwner { gpToken = IGP(_gp); traits = ITraits(_traits); wndNFT = IWnD(_wnd); tower = ITower(_tower); alter = ISacrificialAlter(_alter); } /** EXTERNAL */ function getPendingMint(address addr) external view returns (MintCommit memory) { require(_pendingCommitId[addr] != 0, "no pending commits"); return _mintCommits[addr][_pendingCommitId[addr]]; } function hasMintPending(address addr) external view returns (bool) { return _pendingCommitId[addr] != 0; } function canMint(address addr) external view returns (bool) { return _pendingCommitId[addr] != 0 && _commitRandoms[_pendingCommitId[addr]] > 0; } // Seed the current commit id so that pending commits can be revealed function addCommitRandom(uint256 seed) external { require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this"); _commitRandoms[_commitId] = seed; _commitId += 1; } function deleteCommit(address addr) external { require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this"); uint16 commitIdCur = _pendingCommitId[_msgSender()]; require(commitIdCur > 0, "No pending commit"); delete _mintCommits[addr][commitIdCur]; delete _pendingCommitId[addr]; } function forceRevealCommit(address addr) external { require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this"); reveal(addr); } /** Initiate the start of a mint. This action burns $GP, as the intent of committing is that you cannot back out once you've started. * This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this * commit was added to. */ function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant { require(allowCommits, "adding commits disallowed"); require(tx.origin == _msgSender(), "Only EOA"); require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints"); uint16 minted = wndNFT.minted(); uint256 maxTokens = wndNFT.getMaxTokens(); require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); uint256 totalGpCost = 0; // Loop through the amount of for (uint i = 1; i <= amount; i++) { totalGpCost += mintCost(minted + pendingMintAmt + i, maxTokens); } if (totalGpCost > 0) { gpToken.burn(_msgSender(), totalGpCost); gpToken.updateOriginAccess(); } uint16 amt = uint16(amount); _mintCommits[_msgSender()][_commitId] = MintCommit(stake, amt); _pendingCommitId[_msgSender()] = _commitId; pendingMintAmt += amt; emit MintCommitted(_msgSender(), amount); } /** Reveal the commits for this user. This will be when the user gets their NFT, and can only be done when the commit id that * the user is pending for has been assigned a random seed. */ function mintReveal() external whenNotPaused nonReentrant { require(tx.origin == _msgSender(), "Only EOA1"); reveal(_msgSender()); } function reveal(address addr) internal { uint16 commitIdCur = _pendingCommitId[addr]; require(commitIdCur > 0, "No pending commit"); require(_commitRandoms[commitIdCur] > 0, "random seed not set"); uint16 minted = wndNFT.minted(); MintCommit memory commit = _mintCommits[addr][commitIdCur]; pendingMintAmt -= commit.amount; uint16[] memory tokenIds = new uint16[](commit.amount); uint256 seed = _commitRandoms[commitIdCur]; for (uint k = 0; k < commit.amount; k++) { minted++; // scramble the random so the steal / treasure mechanic are different per mint seed = uint256(keccak256(abi.encode(seed, addr))); address recipient = selectRecipient(seed); if(recipient != addr && alter.balanceOf(addr, treasureChestTypeId) > 0) { // If the mint is going to be stolen, there's a 50% chance // a dragon will prefer a treasure chest over it if(seed & 1 == 1) { alter.safeTransferFrom(addr, recipient, treasureChestTypeId, 1, ""); recipient = addr; } } tokenIds[k] = minted; if (!commit.stake || recipient != addr) { wndNFT.mint(recipient, seed); } else { wndNFT.mint(address(tower), seed); } } wndNFT.updateOriginAccess(tokenIds); if(commit.stake) { tower.addManyToTowerAndFlight(addr, tokenIds); } delete _mintCommits[addr][commitIdCur]; delete _pendingCommitId[addr]; emit MintCommitted(addr, tokenIds.length); } /** * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId, uint256 maxTokens) public view returns (uint256) { if (tokenId <= maxTokens * 8 / 20) return 24000 ether; if (tokenId <= maxTokens * 11 / 20) return 36000 ether; if (tokenId <= maxTokens * 14 / 20) return 48000 ether; if (tokenId <= maxTokens * 17 / 20) return 60000 ether; // if (tokenId > maxTokens * 17 / 20) return maxGpCost; } function payTribute(uint256 gpAmt) external whenNotPaused nonReentrant { require(tx.origin == _msgSender(), "Only EOA"); uint16 minted = wndNFT.minted(); uint256 maxTokens = wndNFT.getMaxTokens(); uint256 gpMintCost = mintCost(minted, maxTokens); require(gpMintCost > 0, "Sacrificial alter currently closed"); require(gpAmt >= gpMintCost, "Not enough gp given"); gpToken.burn(_msgSender(), gpAmt); if(gpAmt < gpMintCost * 2) { alter.mint(1, 1, _msgSender()); } else { alter.mint(2, 1, _msgSender()); } } function makeTreasureChests(uint16 qty) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(treasureChestTypeId > 0, "DEVS DO SOMETHING"); // $GP exchange amount handled within alter contract // Will fail if sender doesn't have enough $GP // Transfer does not need approved, // as there is established trust between this contract and the alter contract alter.mint(treasureChestTypeId, qty, _msgSender()); } function sellTreasureChests(uint16 qty) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(treasureChestTypeId > 0, "DEVS DO SOMETHING"); // $GP exchange amount handled within alter contract alter.burn(treasureChestTypeId, qty, _msgSender()); } function sacrifice(uint256 tokenId, uint256 gpAmt) external whenNotPaused nonReentrant { require(tx.origin == _msgSender(), "Only EOA"); uint64 lastTokenWrite = wndNFT.getTokenWriteBlock(tokenId); // Must check this, as getTokenTraits will be allowed since this contract is an admin require(lastTokenWrite < block.number, "hmmmm what doing?"); IWnD.WizardDragon memory nft = wndNFT.getTokenTraits(tokenId); uint16 minted = wndNFT.minted(); uint256 maxTokens = wndNFT.getMaxTokens(); uint256 gpMintCost = mintCost(minted, maxTokens); require(gpMintCost > 0, "Sacrificial alter currently closed"); if(nft.isWizard) { // Wizard sacrifice requires 3x $GP curve require(gpAmt >= gpMintCost * 3, "not enough gp provided"); gpToken.burn(_msgSender(), gpAmt); // This will check if origin is the owner of the token wndNFT.burn(tokenId); alter.mint(3, 1, _msgSender()); } else { // Dragon sacrifice requires 4x $GP curve require(gpAmt >= gpMintCost * 4, "not enough gp provided"); gpToken.burn(_msgSender(), gpAmt); // This will check if origin is the owner of the token wndNFT.burn(tokenId); alter.mint(4, 1, _msgSender()); } } /** INTERNAL */ /** * the first 25% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked dragon * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Dragon thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = tower.randomDragonOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** ADMIN */ /** * enables owner to pause / unpause contract */ function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); } function setMaxGpCost(uint256 _amount) external requireContractsSet onlyOwner { maxGpCost = _amount; } function setTreasureChestId(uint256 typeId) external onlyOwner { treasureChestTypeId = typeId; } function setAllowCommits(bool allowed) external onlyOwner { allowCommits = allowed; } /** Allow the contract owner to set the pending mint amount. * This allows any long-standing pending commits to be overwritten, say for instance if the max supply has been * reached but there are many stale pending commits, it could be used to free up those spaces if needed/desired by the community. * This function should not be called lightly, this will have negative consequences on the game. */ function setPendingMintAmt(uint256 pendingAmt) external onlyOwner { pendingMintAmt = uint16(pendingAmt); } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT 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: 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 LICENSE pragma solidity ^0.8.0; interface IWnDGame { } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITower { function addManyToTowerAndFlight(address account, uint16[] calldata tokenIds) external; function randomDragonOwner(uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IGP { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function updateOriginAccess() external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IWnD is IERC721Enumerable { // game data storage struct WizardDragon { bool isWizard; uint8 body; uint8 head; uint8 spell; uint8 eyes; uint8 neck; uint8 mouth; uint8 wand; uint8 tail; uint8 rankIndex; } function minted() external returns (uint16); function updateOriginAccess(uint16[] memory tokenIds) external; function mint(address recipient, uint256 seed) external; function burn(uint256 tokenId) external; function getMaxTokens() external view returns (uint256); function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (WizardDragon memory); function getTokenWriteBlock(uint256 tokenId) external view returns(uint64); function isWizard(uint256 tokenId) external view returns(bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ISacrificialAlter { function mint(uint256 typeId, uint16 qty, address recipient) external; function burn(uint256 typeId, uint16 qty, address burnFrom) external; function updateOriginAccess() external; function balanceOf(address account, uint256 id) external returns (uint256); function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) external; } pragma solidity ^0.8.0; interface IRandomizer { function random() external returns (uint256); } // 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; 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); }
scramble the random so the steal / treasure mechanic are different per mint If the mint is going to be stolen, there's a 50% chance a dragon will prefer a treasure chest over it
function reveal(address addr) internal { uint16 commitIdCur = _pendingCommitId[addr]; require(commitIdCur > 0, "No pending commit"); require(_commitRandoms[commitIdCur] > 0, "random seed not set"); uint16 minted = wndNFT.minted(); MintCommit memory commit = _mintCommits[addr][commitIdCur]; pendingMintAmt -= commit.amount; uint16[] memory tokenIds = new uint16[](commit.amount); uint256 seed = _commitRandoms[commitIdCur]; for (uint k = 0; k < commit.amount; k++) { minted++; seed = uint256(keccak256(abi.encode(seed, addr))); address recipient = selectRecipient(seed); if(recipient != addr && alter.balanceOf(addr, treasureChestTypeId) > 0) { if(seed & 1 == 1) { alter.safeTransferFrom(addr, recipient, treasureChestTypeId, 1, ""); recipient = addr; } } tokenIds[k] = minted; if (!commit.stake || recipient != addr) { wndNFT.mint(recipient, seed); wndNFT.mint(address(tower), seed); } } wndNFT.updateOriginAccess(tokenIds); if(commit.stake) { tower.addManyToTowerAndFlight(addr, tokenIds); } delete _mintCommits[addr][commitIdCur]; delete _pendingCommitId[addr]; emit MintCommitted(addr, tokenIds.length); }
254,401
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul // WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that // requires ABIEncoderV2. Exercise caution when calling that specific function. pragma experimental ABIEncoderV2; interface DharmaSmartWalletImplementationV1Interface { event CallSuccess( bytes32 actionID, bool rolledBack, uint256 nonce, address to, uint256 value, bytes data, bytes returnData ); event CallFailure( bytes32 actionID, uint256 nonce, address to, uint256 value, bytes data, string revertReason ); // ABIEncoderV2 uses an array of Calls for executing generic batch calls. struct Call { address to; uint96 value; bytes data; } // ABIEncoderV2 uses an array of CallReturns for handling generic batch calls. struct CallReturn { bool ok; bytes returnData; } function withdrawEther( uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function executeAction( address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function recover(address newUserSigningKey) external; function executeActionWithAtomicBatchCalls( Call[] calldata calls, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool[] memory ok, bytes[] memory returnData); function getNextGenericActionID( address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getGenericActionID( address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getNextGenericAtomicBatchActionID( Call[] calldata calls, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getGenericAtomicBatchActionID( Call[] calldata calls, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV3Interface { event Cancel(uint256 cancelledNonce); event EthWithdrawal(uint256 amount, address recipient); } interface DharmaSmartWalletImplementationV4Interface { event Escaped(); function setEscapeHatch( address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function removeEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function permanentlyDisableEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function escape(address token) external; } interface DharmaSmartWalletImplementationV7Interface { // Fires when a new user signing key is set on the smart wallet. event NewUserSigningKey(address userSigningKey); // Fires when an error occurs as part of an attempted action. event ExternalError(address indexed source, string revertReason); // The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets. enum AssetType { DAI, USDC, ETH, SAI } // Actions, or protected methods (i.e. not deposits) each have an action type. enum ActionType { Cancel, SetUserSigningKey, Generic, GenericAtomicBatch, SAIWithdrawal, USDCWithdrawal, ETHWithdrawal, SetEscapeHatch, RemoveEscapeHatch, DisableEscapeHatch, DAIWithdrawal, SignatureVerification, TradeEthForDai, DAIBorrow, USDCBorrow } function initialize(address userSigningKey) external; function repayAndDeposit() external; function withdrawDai( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function withdrawUSDC( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function cancel( uint256 minimumActionGas, bytes calldata signature ) external; function setUserSigningKey( address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function migrateSaiToDai() external; function migrateCSaiToDDai() external; function migrateCDaiToDDai() external; function migrateCUSDCToDUSDC() external; function getBalances() external view returns ( uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns zero ); function getUserSigningKey() external view returns (address userSigningKey); function getNonce() external view returns (uint256 nonce); function getNextCustomActionID( ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getCustomActionID( ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getVersion() external pure returns (uint256 version); } interface DharmaSmartWalletImplementationV8Interface { function tradeEthForDaiAndMintDDai( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function getNextEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV12Interface { function setApproval(address token, uint256 amount) external; } interface DharmaSmartWalletImplementationV13Interface { function redeemAllDDai() external; function redeemAllDUSDC() external; } interface ERC20Interface { function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); } interface ERC1271Interface { function isValidSignature( bytes calldata data, bytes calldata signature ) external view returns (bytes4 magicValue); } interface DTokenInterface { // These external functions trigger accrual on the dToken and backing cToken. function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); // These external functions only trigger accrual on the dToken. function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); // View and pure functions do not trigger accrual on the dToken or the cToken. function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance); } interface DharmaKeyRegistryInterface { function getKey() external view returns (address key); } interface DharmaEscapeHatchRegistryInterface { function setEscapeHatch(address newEscapeHatch) external; function removeEscapeHatch() external; function permanentlyDisableEscapeHatch() external; function getEscapeHatch() external view returns ( bool exists, address escapeHatch ); } interface RevertReasonHelperInterface { function reason(uint256 code) external pure returns (string memory); } interface EtherizedInterface { function triggerEtherTransfer( address payable target, uint256 value ) external returns (bool success); } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } library ECDSA { function recover( bytes32 hash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(hash, v, r, s); } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } contract Etherized is EtherizedInterface { address private constant _ETHERIZER = address( 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); function triggerEtherTransfer( address payable target, uint256 amount ) external returns (bool success) { require(msg.sender == _ETHERIZER, "Etherized: only callable by Etherizer"); (success, ) = target.call.value(amount)(""); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } /** * @title DharmaSmartWalletImplementationV14 * @author 0age * @notice The V14 implementation for the Dharma smart wallet is a non-custodial, * meta-transaction-enabled wallet with helper functions to facilitate lending * funds through Dharma Dai and Dharma USD Coin (which in turn use CompoundV2), * and with an added security backstop provided by Dharma Labs prior to making * withdrawals. It adds support for Dharma Dai and Dharma USD Coin - they employ * the respective cTokens as backing tokens and mint and redeem them internally * as interest-bearing collateral. This implementation also contains methods to * support account recovery, escape hatch functionality, and generic actions, * including in an atomic batch. The smart wallet instances utilizing this * implementation are deployed through the Dharma Smart Wallet Factory via * `CREATE2`, which allows for their address to be known ahead of time, and any * Dai or USDC that has already been sent into that address will automatically * be deposited into the respective Dharma Token upon deployment of the new * smart wallet instance. V14 allows for Ether transfers as part of generic * actions, supports "simulation" of generic batch actions, and revises escape * hatch functionality to support arbitrary token withdrawals. */ contract DharmaSmartWalletImplementationV14 is DharmaSmartWalletImplementationV1Interface, DharmaSmartWalletImplementationV3Interface, DharmaSmartWalletImplementationV4Interface, DharmaSmartWalletImplementationV7Interface, DharmaSmartWalletImplementationV8Interface, DharmaSmartWalletImplementationV12Interface, DharmaSmartWalletImplementationV13Interface, ERC1271Interface, Etherized { using Address for address; using ECDSA for bytes32; // WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS! // The user signing key associated with this account is in storage slot 0. // It is the core differentiator when it comes to the account in question. address private _userSigningKey; // The nonce associated with this account is in storage slot 1. Every time a // signature is submitted, it must have the appropriate nonce, and once it has // been accepted the nonce will be incremented. uint256 private _nonce; // The self-call context flag is in storage slot 2. Some protected functions // may only be called externally from calls originating from other methods on // this contract, which enables appropriate exception handling on reverts. // Any storage should only be set immediately preceding a self-call and should // be cleared upon entering the protected function being called. bytes4 internal _selfCallContext; // END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE! // The smart wallet version will be used when constructing valid signatures. uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 14; // DharmaKeyRegistryV2 holds a public key for verifying meta-transactions. DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = ( DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52) ); // Account recovery is facilitated using a hard-coded recovery manager, // controlled by Dharma and implementing appropriate timelocks. address internal constant _ACCOUNT_RECOVERY_MANAGER = address( 0x0000000000DfEd903aD76996FC07BF89C0127B1E ); // Users can designate an "escape hatch" account with the ability to sweep any // funds from their smart wallet by using the Dharma Escape Hatch Registry. DharmaEscapeHatchRegistryInterface internal constant _ESCAPE_HATCH_REGISTRY = ( DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8) ); // Interface with dDai and dUSDC contracts. DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 // mainnet ); DTokenInterface internal constant _DUSDC = DTokenInterface( 0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet ); // The "revert reason helper" contains a collection of revert reason strings. RevertReasonHelperInterface internal constant _REVERT_REASON_HELPER = ( RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4) ); // The "Trade Bot" enables limit orders using unordered meta-transactions. address internal constant _TRADE_BOT = address( 0x8bFB7aC05bF9bDC6Bc3a635d4dd209c8Ba39E554 ); // ERC-1271 must return this magic value when `isValidSignature` is called. bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b); // Specify the amount of gas to supply when making Ether transfers. uint256 private constant _ETH_TRANSFER_GAS = 4999; /** * @notice Accept Ether in the fallback. */ function () external payable {} /** * @notice In the initializer, set up the initial user signing key. Note that * this initializer is only callable while the smart wallet instance is still * in the contract creation phase. * @param userSigningKey address The initial user signing key for the smart * wallet. */ function initialize(address userSigningKey) external { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set up the user's signing key and emit a corresponding event. _setUserSigningKey(userSigningKey); } /** * @notice Redeem all Dharma Dai held by this account for Dai. */ function redeemAllDDai() external { _withdrawMaxFromDharmaToken(AssetType.DAI); } /** * @notice Redeem all Dharma USD Coin held by this account for USDC. */ function redeemAllDUSDC() external { _withdrawMaxFromDharmaToken(AssetType.USDC); } /** * @notice This call is no longer supported. */ function repayAndDeposit() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function withdrawDai( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function withdrawUSDC( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { revert("Deprecated."); } /** * @notice Withdraw Ether to a provided recipient address by transferring it * to a recipient. * @param amount uint256 The amount of Ether to withdraw. * @param recipient address The account to transfer the Ether to. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return True if the transfer succeeded, otherwise false. */ function withdrawEther( uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.ETHWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that a non-zero amount of Ether has been supplied. if (amount == 0) { revert(_revertReason(4)); } // Ensure that a non-zero recipient has been supplied. if (recipient == address(0)) { revert(_revertReason(1)); } // Attempt to transfer Ether to the recipient and emit an appropriate event. ok = _transferETH(recipient, amount); } /** * @notice Allow a signatory to increment the nonce at any point. The current * nonce needs to be provided as an argument to the signature so as not to * enable griefing attacks. All arguments can be omitted if called directly. * No value is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param signature bytes A signature that resolves to either the public key * set for this account in storage slot zero, `_userSigningKey`, or the public * key returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function cancel( uint256 minimumActionGas, bytes calldata signature ) external { // Get the current nonce. uint256 nonceToCancel = _nonce; // Ensure the caller or the supplied signature is valid and increment nonce. _validateActionAndIncrementNonce( ActionType.Cancel, abi.encode(), minimumActionGas, signature, signature ); // Emit an event to validate that the nonce is no longer valid. emit Cancel(nonceToCancel); } /** * @notice This call is no longer supported. */ function executeAction( address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { revert("Deprecated."); } /** * @notice Allow signatory to set a new user signing key. The current nonce * needs to be provided as an argument to the signature so as not to enable * griefing attacks. No value is returned from this function - it will either * succeed or revert. * @param userSigningKey address The new user signing key to set on this smart * wallet. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function setUserSigningKey( address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.SetUserSigningKey, abi.encode(userSigningKey), minimumActionGas, userSignature, dharmaSignature ); // Set new user signing key on smart wallet and emit a corresponding event. _setUserSigningKey(userSigningKey); } /** * @notice Set a dedicated address as the "escape hatch" account. This account * can then call `escape(address token)` at any point to "sweep" the entire * balance of the token (or Ether given null address) from the smart wallet. * This function call will revert if the smart wallet has previously called * `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch. * No value is returned from this function - it will either succeed or revert. * @param account address The account to set as the escape hatch account. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function setEscapeHatch( address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.SetEscapeHatch, abi.encode(account), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an escape hatch account has been provided. if (account == address(0)) { revert(_revertReason(5)); } // Set a new escape hatch for the smart wallet unless it has been disabled. _ESCAPE_HATCH_REGISTRY.setEscapeHatch(account); } /** * @notice Remove the "escape hatch" account if one is currently set. This * function call will revert if the smart wallet has previously called * `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch. * No value is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function removeEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.RemoveEscapeHatch, abi.encode(), minimumActionGas, userSignature, dharmaSignature ); // Remove the escape hatch for the smart wallet if one is currently set. _ESCAPE_HATCH_REGISTRY.removeEscapeHatch(); } /** * @notice Permanently disable the "escape hatch" mechanism for this smart * wallet. This function call will revert if the smart wallet has already * called `permanentlyDisableEscapeHatch` at any point in the past. No value * is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function permanentlyDisableEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.DisableEscapeHatch, abi.encode(), minimumActionGas, userSignature, dharmaSignature ); // Permanently disable the escape hatch mechanism for this smart wallet. _ESCAPE_HATCH_REGISTRY.permanentlyDisableEscapeHatch(); } /** * @notice This call is no longer supported. */ function tradeEthForDaiAndMintDDai( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { revert("Deprecated."); } /** * @notice Allow the designated escape hatch account to redeem and "sweep" * the total token balance or Ether balance (by supplying the null address) * from the smart wallet. The call will revert for any other caller, or if * there is no escape hatch account on this smart wallet. An `Escaped` event * will be emitted. No value is returned from this function - it will either * succeed or revert. */ function escape(address token) external { // Get the escape hatch account, if one exists, for this account. (bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch(); // Ensure that an escape hatch is currently set for this smart wallet. if (!exists) { revert(_revertReason(6)); } // Ensure that the escape hatch account is the caller. if (msg.sender != escapeHatch) { revert(_revertReason(7)); } if (token == address(0)) { // Determine if there is Ether at this address that should be transferred. uint256 balance = address(this).balance; if (balance > 0) { // Attempt to transfer any Ether to caller and emit an appropriate event. _transferETH(msg.sender, balance); } } else { // Attempt to transfer all tokens to the caller. _transferMax(ERC20Interface(address(token)), msg.sender, false); } // Emit an `Escaped` event. emit Escaped(); } /** * @notice Allow the account recovery manager to set a new user signing key on * the smart wallet. The call will revert for any other caller. The account * recovery manager implements a set of controls around the process, including * a timelock and an option to permanently opt out of account recover. No * value is returned from this function - it will either succeed or revert. * @param newUserSigningKey address The new user signing key to set on this * smart wallet. */ function recover(address newUserSigningKey) external { // Only the Account Recovery Manager contract may call this function. if (msg.sender != _ACCOUNT_RECOVERY_MANAGER) { revert(_revertReason(8)); } // Increment nonce to prevent signature reuse should original key be reset. _nonce++; // Set up the user's new dharma key and emit a corresponding event. _setUserSigningKey(newUserSigningKey); } function setApproval(address token, uint256 amount) external { // Only the Trade Bot contract may call this function. if (msg.sender != _TRADE_BOT) { revert("Only the Trade Bot may call this function."); } ERC20Interface(token).approve(_TRADE_BOT, amount); } /** * @notice This call is no longer supported. */ function migrateSaiToDai() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function migrateCSaiToDDai() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function migrateCDaiToDDai() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function migrateCUSDCToDUSDC() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getBalances() external view returns ( uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns 0 ) { revert("Deprecated."); } /** * @notice View function for getting the current user signing key for the * smart wallet. * @return The current user signing key. */ function getUserSigningKey() external view returns (address userSigningKey) { userSigningKey = _userSigningKey; } /** * @notice View function for getting the current nonce of the smart wallet. * This nonce is incremented whenever an action is taken that requires a * signature and/or a specific caller. * @return The current nonce. */ function getNonce() external view returns (uint256 nonce) { nonce = _nonce; } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for the corresponding action. Any nonce value * may be supplied, which enables constructing valid message hashes for * multiple future actions ahead of time. * @param action uint8 The type of action, designated by it's index. Valid * custom actions include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextCustomActionID( ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( action, _validateCustomActionTypeAndGetArguments(action, amount, recipient), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for the corresponding action. The current nonce * will be used, which means that it will only be valid for the next action * taken. * @param action uint8 The type of action, designated by it's index. Valid * custom actions include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getCustomActionID( ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( action, _validateCustomActionTypeAndGetArguments(action, amount, recipient), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice This call is no longer supported. */ function getNextGenericActionID( address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getGenericActionID( address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getNextEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice View function that implements ERC-1271 and validates a set of * signatures, one from the owner (using ERC-1271 as well if the user signing * key is a contract) and one from the Dharma Key Registry against the * supplied data. The data must be ABI encoded as (bytes32, bytes), where the * first bytes32 parameter represents the hash digest for validating the * supplied signatures and the second bytes parameter contains context for the * requested validation. The two signatures are packed together, with the one * from Dharma coming first and that from the user coming second - this is so * that, in future versions, multiple user signatures may be supplied if the * associated key ring requires them. * @param data bytes The data used to validate the signature. * @param signatures bytes The two signatures, each 65 bytes - one from the * owner (using ERC-1271 as well if the user signing key is a contract) and * one from the Dharma Key Registry. * @return The 4-byte magic value to signify a valid signature in ERC-1271, if * the signatures are both valid. */ function isValidSignature( bytes calldata data, bytes calldata signatures ) external view returns (bytes4 magicValue) { // Get message hash digest and any additional context from data argument. bytes32 digest; bytes memory context; if (data.length == 32) { digest = abi.decode(data, (bytes32)); } else { if (data.length < 64) { revert(_revertReason(30)); } (digest, context) = abi.decode(data, (bytes32, bytes)); } // Get Dharma signature & user signature from combined signatures argument. if (signatures.length != 130) { revert(_revertReason(11)); } bytes memory signaturesInMemory = signatures; bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signaturesInMemory, 0x20)) s := mload(add(signaturesInMemory, 0x40)) v := byte(0, mload(add(signaturesInMemory, 0x60))) } bytes memory dharmaSignature = abi.encodePacked(r, s, v); assembly { r := mload(add(signaturesInMemory, 0x61)) s := mload(add(signaturesInMemory, 0x81)) v := byte(0, mload(add(signaturesInMemory, 0xa1))) } bytes memory userSignature = abi.encodePacked(r, s, v); // Validate user signature with `SignatureVerification` as the action type. if ( !_validateUserSignature( digest, ActionType.SignatureVerification, context, _userSigningKey, userSignature ) ) { revert(_revertReason(12)); } // Recover Dharma signature against key returned from Dharma Key Registry. if (_getDharmaSigningKey() != digest.recover(dharmaSignature)) { revert(_revertReason(13)); } // Return the ERC-1271 magic value to indicate success. magicValue = _ERC_1271_MAGIC_VALUE; } /** * @notice View function for getting the current Dharma Smart Wallet * implementation contract address set on the upgrade beacon. * @return The current Dharma Smart Wallet implementation contract. */ function getImplementation() external view returns (address implementation) { (bool ok, bytes memory returnData) = address( 0x000000000026750c571ce882B17016557279ADaa ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } /** * @notice Pure function for getting the current Dharma Smart Wallet version. * @return The current Dharma Smart Wallet version. */ function getVersion() external pure returns (uint256 version) { version = _DHARMA_SMART_WALLET_VERSION; } /** * @notice Perform a series of generic calls to other contracts. If any call * fails during execution, the preceding calls will be rolled back, but their * original return data will still be accessible. Calls that would otherwise * occur after the failed call will not be executed. Note that accounts with * no code may not be specified unless value is included, nor may the smart * wallet itself or the escape hatch registry. In order to increment the nonce * and invalidate the signatures, a call to this function with valid targets, * signatutes, and gas will always succeed. To determine whether each call * made as part of the action was successful or not, either the corresponding * return value or `CallSuccess` and `CallFailure` events can be used - note * that even calls that return a success status will be rolled back unless all * of the calls returned a success status. Finally, note that this function * must currently be implemented as a public function (instead of as an * external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. */ function executeActionWithAtomicBatchCalls( Call[] memory calls, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) public returns (bool[] memory ok, bytes[] memory returnData) { // Ensure that each `to` address is a contract and is not this contract. for (uint256 i = 0; i < calls.length; i++) { if (calls[i].value == 0) { _ensureValidGenericCallTarget(calls[i].to); } } // Ensure caller and/or supplied signatures are valid and increment nonce. (bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce( ActionType.GenericAtomicBatch, abi.encode(calls), minimumActionGas, userSignature, dharmaSignature ); // Note: from this point on, there are no reverts (apart from out-of-gas or // call-depth-exceeded) originating from this contract. However, one of the // calls may revert, in which case the function will return `false`, along // with the revert reason encoded as bytes, and fire an CallFailure event. // Specify length of returned values in order to work with them in memory. ok = new bool[](calls.length); returnData = new bytes[](calls.length); // Set self-call context to call _executeActionWithAtomicBatchCallsAtomic. _selfCallContext = this.executeActionWithAtomicBatchCalls.selector; // Make the atomic self-call - if any call fails, calls that preceded it // will be rolled back and calls that follow it will not be made. (bool externalOk, bytes memory rawCallResults) = address(this).call( abi.encodeWithSelector( this._executeActionWithAtomicBatchCallsAtomic.selector, calls ) ); // Ensure that self-call context has been cleared. if (!externalOk) { delete _selfCallContext; } // Parse data returned from self-call into each call result and store / log. CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[])); for (uint256 i = 0; i < callResults.length; i++) { Call memory currentCall = calls[i]; // Set the status and the return data / revert reason from the call. ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData; // Emit CallSuccess or CallFailure event based on the outcome of the call. if (callResults[i].ok) { // Note: while the call succeeded, the action may still have "failed". emit CallSuccess( actionID, !externalOk, // If another call failed this will have been rolled back nonce, currentCall.to, uint256(currentCall.value), currentCall.data, callResults[i].returnData ); } else { // Note: while the call failed, the nonce will still be incremented, // which will invalidate all supplied signatures. emit CallFailure( actionID, nonce, currentCall.to, uint256(currentCall.value), currentCall.data, _decodeRevertReason(callResults[i].returnData) ); // exit early - any calls after the first failed call will not execute. break; } } } /** * @notice Protected function that can only be called from * `executeActionWithAtomicBatchCalls` on this contract. It will attempt to * perform each specified call, populating the array of results as it goes, * unless a failure occurs, at which point it will revert and "return" the * array of results as revert data. Otherwise, it will simply return the array * upon successful completion of each call. Finally, note that this function * must currently be implemented as a public function (instead of as an * external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. If any of the calls fail, the array will be returned as revert * data. */ function _executeActionWithAtomicBatchCallsAtomic( Call[] memory calls ) public returns (CallReturn[] memory callResults) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector); bool rollBack = false; callResults = new CallReturn[](calls.length); for (uint256 i = 0; i < calls.length; i++) { // Perform low-level call and set return values using result. (bool ok, bytes memory returnData) = calls[i].to.call.value( uint256(calls[i].value) )(calls[i].data); callResults[i] = CallReturn({ok: ok, returnData: returnData}); if (!ok) { // Exit early - any calls after the first failed call will not execute. rollBack = true; break; } } if (rollBack) { // Wrap in length encoding and revert (provide bytes instead of a string). bytes memory callResultsBytes = abi.encode(callResults); assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) } } } /** * @notice Simulate a series of generic calls to other contracts. Signatures * are not required, but all calls will be rolled back (and calls will only be * simulated up until a failing call is encountered). * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. */ function simulateActionWithAtomicBatchCalls( Call[] memory calls ) public /* view */ returns (bool[] memory ok, bytes[] memory returnData) { // Ensure that each `to` address is a contract and is not this contract. for (uint256 i = 0; i < calls.length; i++) { if (calls[i].value == 0) { _ensureValidGenericCallTarget(calls[i].to); } } // Specify length of returned values in order to work with them in memory. ok = new bool[](calls.length); returnData = new bytes[](calls.length); // Set self-call context to call _simulateActionWithAtomicBatchCallsAtomic. _selfCallContext = this.simulateActionWithAtomicBatchCalls.selector; // Make the atomic self-call - if any call fails, calls that preceded it // will be rolled back and calls that follow it will not be made. (bool mustBeFalse, bytes memory rawCallResults) = address(this).call( abi.encodeWithSelector( this._simulateActionWithAtomicBatchCallsAtomic.selector, calls ) ); // Note: this should never be the case, but check just to be extra safe. if (mustBeFalse) { revert("Simulation call must revert!"); } // Ensure that self-call context has been cleared. delete _selfCallContext; // Parse data returned from self-call into each call result and store / log. CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[])); for (uint256 i = 0; i < callResults.length; i++) { // Set the status and the return data / revert reason from the call. ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData; if (!callResults[i].ok) { // exit early - any calls after the first failed call will not execute. break; } } } /** * @notice Protected function that can only be called from * `simulateActionWithAtomicBatchCalls` on this contract. It will attempt to * perform each specified call, populating the array of results as it goes, * unless a failure occurs, at which point it will revert and "return" the * array of results as revert data. Regardless, it will roll back all calls at * the end of execution — in other words, this call always reverts. * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. If any of the calls fail, the array will be returned as revert * data. */ function _simulateActionWithAtomicBatchCallsAtomic( Call[] memory calls ) public returns (CallReturn[] memory callResults) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.simulateActionWithAtomicBatchCalls.selector); callResults = new CallReturn[](calls.length); for (uint256 i = 0; i < calls.length; i++) { // Perform low-level call and set return values using result. (bool ok, bytes memory returnData) = calls[i].to.call.value( uint256(calls[i].value) )(calls[i].data); callResults[i] = CallReturn({ok: ok, returnData: returnData}); if (!ok) { // Exit early - any calls after the first failed call will not execute. break; } } // Wrap in length encoding and revert (provide bytes instead of a string). bytes memory callResultsBytes = abi.encode(callResults); assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) } } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for a given generic atomic batch action. The * current nonce will be used, which means that it will only be valid for the * next action taken. Finally, note that this function must currently be * implemented as a public function (instead of as an external one) due to an * ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextGenericAtomicBatchActionID( Call[] memory calls, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.GenericAtomicBatch, abi.encode(calls), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for a given generic atomic batch action. Any * nonce value may be supplied, which enables constructing valid message * hashes for multiple future actions ahead of time. Finally, note that this * function must currently be implemented as a public function (instead of as * an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getGenericAtomicBatchActionID( Call[] memory calls, uint256 nonce, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.GenericAtomicBatch, abi.encode(calls), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice Internal function for setting a new user signing key. Called by the * initializer, by the `setUserSigningKey` function, and by the `recover` * function. A `NewUserSigningKey` event will also be emitted. * @param userSigningKey address The new user signing key to set on this smart * wallet. */ function _setUserSigningKey(address userSigningKey) internal { // Ensure that a user signing key is set on this smart wallet. if (userSigningKey == address(0)) { revert(_revertReason(14)); } _userSigningKey = userSigningKey; emit NewUserSigningKey(userSigningKey); } /** * @notice Internal function for withdrawing the total underlying asset * balance from the corresponding dToken. Note that the requested balance may * not be currently available on Compound, which will cause the withdrawal to * fail. * @param asset uint256 The asset's ID, either Dai (0) or USDC (1). */ function _withdrawMaxFromDharmaToken(AssetType asset) internal { // Get dToken address for the asset type. (No custom ETH withdrawal action.) address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC); // Try to retrieve the current dToken balance for this account. ERC20Interface dTokenBalance; (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( dTokenBalance.balanceOf.selector, address(this) )); uint256 redeemAmount = 0; if (ok && data.length == 32) { redeemAmount = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check - log an ExternalError. _checkDharmaTokenInteractionAndLogAnyErrors( asset, dTokenBalance.balanceOf.selector, ok, data ); } // Only perform the call to redeem if there is a non-zero balance. if (redeemAmount > 0) { // Attempt to redeem the underlying balance from the dToken contract. (ok, data) = dToken.call(abi.encodeWithSelector( // Function selector is the same for all dTokens, so just use dDai's. _DDAI.redeem.selector, redeemAmount )); // Log an external error if something went wrong with the attempt. _checkDharmaTokenInteractionAndLogAnyErrors( asset, _DDAI.redeem.selector, ok, data ); } } /** * @notice Internal function for transferring the total underlying balance of * the corresponding token to a designated recipient. It will return true if * tokens were successfully transferred (or there is no balance), signified by * the boolean returned by the transfer function, or the call status if the * `suppressRevert` boolean is set to true. * @param token IERC20 The interface of the token in question. * @param recipient address The account that will receive the tokens. * @param suppressRevert bool A boolean indicating whether reverts should be * suppressed or not. Used by the escape hatch so that a problematic transfer * will not block the rest of the call from executing. * @return True if tokens were successfully transferred or if there is no * balance, else false. */ function _transferMax( ERC20Interface token, address recipient, bool suppressRevert ) internal returns (bool success) { // Get the current balance on the smart wallet for the supplied ERC20 token. uint256 balance = 0; bool balanceCheckWorked = true; if (!suppressRevert) { balance = token.balanceOf(address(this)); } else { // Try to retrieve current token balance for this account with 1/2 gas. (bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.balanceOf.selector, address(this)) ); if (ok && data.length >= 32) { balance = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check. balanceCheckWorked = false; } } // Only perform the call to transfer if there is a non-zero balance. if (balance > 0) { if (!suppressRevert) { // Perform the transfer and pass along the returned boolean (or revert). success = token.transfer(recipient, balance); } else { // Attempt transfer with 1/2 gas, allow reverts, and return call status. (success, ) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.transfer.selector, recipient, balance) ); } } else { // Skip the transfer and return true as long as the balance check worked. success = balanceCheckWorked; } } /** * @notice Internal function for transferring Ether to a designated recipient. * It will return true and emit an `EthWithdrawal` event if Ether was * successfully transferred - otherwise, it will return false and emit an * `ExternalError` event. * @param recipient address payable The account that will receive the Ether. * @param amount uint256 The amount of Ether to transfer. * @return True if Ether was successfully transferred, else false. */ function _transferETH( address payable recipient, uint256 amount ) internal returns (bool success) { // Attempt to transfer any Ether to caller and emit an event if it fails. (success, ) = recipient.call.gas(_ETH_TRANSFER_GAS).value(amount)(""); if (!success) { emit ExternalError(recipient, _revertReason(18)); } else { emit EthWithdrawal(amount, recipient); } } /** * @notice Internal function for validating supplied gas (if specified), * retrieving the signer's public key from the Dharma Key Registry, deriving * the action ID, validating the provided caller and/or signatures using that * action ID, and incrementing the nonce. This function serves as the * entrypoint for all protected "actions" on the smart wallet, and is the only * area where these functions should revert (other than due to out-of-gas * errors, which can be guarded against by supplying a minimum action gas * requirement). * @param action uint8 The type of action, designated by it's index. Valid * actions include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return The nonce of the current action (prior to incrementing it). */ function _validateActionAndIncrementNonce( ActionType action, bytes memory arguments, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) internal returns (bytes32 actionID, uint256 actionNonce) { // Ensure that the current gas exceeds the minimum required action gas. // This prevents griefing attacks where an attacker can invalidate a // signature without providing enough gas for the action to succeed. Also // note that some gas will be spent before this check is reached - supplying // ~30,000 additional gas should suffice when submitting transactions. To // skip this requirement, supply zero for the minimumActionGas argument. if (minimumActionGas != 0) { if (gasleft() < minimumActionGas) { revert(_revertReason(19)); } } // Get the current nonce for the action to be performed. actionNonce = _nonce; // Get the user signing key that will be used to verify their signature. address userSigningKey = _userSigningKey; // Get the Dharma signing key that will be used to verify their signature. address dharmaSigningKey = _getDharmaSigningKey(); // Determine the actionID - this serves as the signature hash. actionID = _getActionID( action, arguments, actionNonce, minimumActionGas, userSigningKey, dharmaSigningKey ); // Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID. bytes32 messageHash = actionID.toEthSignedMessageHash(); // Actions other than Cancel require both signatures; Cancel only needs one. if (action != ActionType.Cancel) { // Validate user signing key signature unless it is `msg.sender`. if (msg.sender != userSigningKey) { if ( !_validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_revertReason(20)); } } // Validate Dharma signing key signature unless it is `msg.sender`. if (msg.sender != dharmaSigningKey) { if (dharmaSigningKey != messageHash.recover(dharmaSignature)) { revert(_revertReason(21)); } } } else { // Validate signing key signature unless user or Dharma is `msg.sender`. if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) { if ( dharmaSigningKey != messageHash.recover(dharmaSignature) && !_validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_revertReason(22)); } } } // Increment nonce in order to prevent reuse of signatures after the call. _nonce++; } /** * @notice Internal function to determine whether a call to a given dToken * succeeded, and to emit a relevant ExternalError event if it failed. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param functionSelector bytes4 The function selector that was called on the * corresponding dToken of the asset type. * @param ok bool A boolean representing whether the call returned or * reverted. * @param data bytes The data provided by the returned or reverted call. * @return True if the interaction was successful, otherwise false. This will * be used to determine if subsequent steps in the action should be attempted * or not, specifically a transfer following a withdrawal. */ function _checkDharmaTokenInteractionAndLogAnyErrors( AssetType asset, bytes4 functionSelector, bool ok, bytes memory data ) internal returns (bool success) { // Log an external error if something went wrong with the attempt. if (ok) { if (data.length == 32) { uint256 amount = abi.decode(data, (uint256)); if (amount > 0) { success = true; } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave no tokens calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave bad data calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); // Decode the revert reason in the event one was returned. string memory revertReason = _decodeRevertReason(data); emit ExternalError( account, string( abi.encodePacked( name, " reverted calling ", functionName, ": ", revertReason ) ) ); } } /** * @notice Internal function to ensure that protected functions can only be * called from this contract and that they have the appropriate context set. * The self-call context is then cleared. It is used as an additional guard * against reentrancy, especially once generic actions are supported by the * smart wallet in future versions. * @param selfCallContext bytes4 The expected self-call context, equal to the * function selector of the approved calling function. */ function _enforceSelfCallFrom(bytes4 selfCallContext) internal { // Ensure caller is this contract and self-call context is correctly set. if (msg.sender != address(this) || _selfCallContext != selfCallContext) { revert(_revertReason(25)); } // Clear the self-call context. delete _selfCallContext; } /** * @notice Internal view function for validating a user's signature. If the * user's signing key does not have contract code, it will be validated via * ecrecover; otherwise, it will be validated using ERC-1271, passing the * message hash that was signed, the action type, and the arguments as data. * @param messageHash bytes32 The message hash that is signed by the user. It * is derived by prefixing (according to EIP-191 0x45) and hashing an actionID * returned from `getCustomActionID`. * @param action uint8 The type of action, designated by it's index. Valid * actions include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. * @return A boolean representing the validity of the supplied user signature. */ function _validateUserSignature( bytes32 messageHash, ActionType action, bytes memory arguments, address userSigningKey, bytes memory userSignature ) internal view returns (bool valid) { if (!userSigningKey.isContract()) { valid = userSigningKey == messageHash.recover(userSignature); } else { bytes memory data = abi.encode(messageHash, action, arguments); valid = ( ERC1271Interface(userSigningKey).isValidSignature( data, userSignature ) == _ERC_1271_MAGIC_VALUE ); } } /** * @notice Internal view function to get the Dharma signing key for the smart * wallet from the Dharma Key Registry. This key can be set for each specific * smart wallet - if none has been set, a global fallback key will be used. * @return The address of the Dharma signing key, or public key corresponding * to the secondary signer. */ function _getDharmaSigningKey() internal view returns ( address dharmaSigningKey ) { dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey(); } /** * @notice Internal view function that, given an action type and arguments, * will return the action ID or message hash that will need to be prefixed * (according to EIP-191 0x45), hashed, and signed by the key designated by * the Dharma Key Registry in order to construct a valid signature for the * corresponding action. The current nonce will be supplied to this function * when reconstructing an action ID during protected function execution based * on the supplied parameters. * @param action uint8 The type of action, designated by it's index. Valid * actions include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param dharmaSigningKey address The address of the secondary key, or public * key corresponding to the secondary signer. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey ) internal view returns (bytes32 actionID) { // actionID is constructed according to EIP-191-0x45 to prevent replays. actionID = keccak256( abi.encodePacked( address(this), _DHARMA_SMART_WALLET_VERSION, userSigningKey, dharmaSigningKey, nonce, minimumActionGas, action, arguments ) ); } /** * @notice Internal pure function to get the dToken address, it's name, and * the name of the called function, based on a supplied asset type and * function selector. It is used to help construct ExternalError events. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param functionSelector bytes4 The function selector that was called on the * corresponding dToken of the asset type. * @return The dToken address, it's name, and the name of the called function. */ function _getDharmaTokenDetails( AssetType asset, bytes4 functionSelector ) internal pure returns ( address account, string memory name, string memory functionName ) { if (asset == AssetType.DAI) { account = address(_DDAI); name = "Dharma Dai"; } else { account = address(_DUSDC); name = "Dharma USD Coin"; } // Note: since both dTokens have the same interface, just use dDai's. if (functionSelector == _DDAI.mint.selector) { functionName = "mint"; } else { if (functionSelector == ERC20Interface(account).balanceOf.selector) { functionName = "balanceOf"; } else { functionName = string(abi.encodePacked( "redeem", functionSelector == _DDAI.redeem.selector ? "" : "Underlying" )); } } } /** * @notice Internal view function to ensure that a given `to` address provided * as part of a generic action is valid. Calls cannot be performed to accounts * without code or back into the smart wallet itself. Additionally, generic * calls cannot supply the address of the Dharma Escape Hatch registry - the * specific, designated functions must be used in order to make calls into it. * @param to address The address that will be targeted by the generic call. */ function _ensureValidGenericCallTarget(address to) internal view { if (!to.isContract()) { revert(_revertReason(26)); } if (to == address(this)) { revert(_revertReason(27)); } if (to == address(_ESCAPE_HATCH_REGISTRY)) { revert(_revertReason(28)); } } /** * @notice Internal pure function to ensure that a given action type is a * "custom" action type (i.e. is not a generic action type) and to construct * the "arguments" input to an actionID based on that action type. * @param action uint8 The type of action, designated by it's index. Valid * custom actions include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for all non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @return A bytes array containing the arguments that will be provided as * a component of the inputs when constructing a custom action ID. */ function _validateCustomActionTypeAndGetArguments( ActionType action, uint256 amount, address recipient ) internal pure returns (bytes memory arguments) { // Ensure that the action type is a valid custom action type. bool validActionType = ( action == ActionType.Cancel || action == ActionType.SetUserSigningKey || action == ActionType.DAIWithdrawal || action == ActionType.USDCWithdrawal || action == ActionType.ETHWithdrawal || action == ActionType.SetEscapeHatch || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ); if (!validActionType) { revert(_revertReason(29)); } // Use action type to determine parameters to include in returned arguments. if ( action == ActionType.Cancel || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ) { // Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch. arguments = abi.encode(); } else if ( action == ActionType.SetUserSigningKey || action == ActionType.SetEscapeHatch ) { // Ignore `amount` parameter for other, non-withdrawal actions. arguments = abi.encode(recipient); } else { // Use both `amount` and `recipient` parameters for withdrawals. arguments = abi.encode(amount, recipient); } } /** * @notice Internal pure function to decode revert reasons. The revert reason * prefix is removed and the remaining string argument is decoded. * @param revertData bytes The raw data supplied alongside the revert. * @return The decoded revert reason string. */ function _decodeRevertReason( bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08) && revertData[1] == byte(0xc3) && revertData[2] == byte(0x79) && revertData[3] == byte(0xa0) ) { // Get the revert reason without the prefix from the revert data. bytes memory revertReasonBytes = new bytes(revertData.length - 4); for (uint256 i = 4; i < revertData.length; i++) { revertReasonBytes[i - 4] = revertData[i]; } // Decode the resultant revert reason as a string. revertReason = abi.decode(revertReasonBytes, (string)); } else { // Simply return the default, with no revert reason. revertReason = _revertReason(uint256(-1)); } } /** * @notice Internal pure function call the revert reason helper contract, * supplying a revert "code" and receiving back a revert reason string. * @param code uint256 The code for the revert reason. * @return The revert reason string. */ function _revertReason( uint256 code ) internal pure returns (string memory reason) { reason = _REVERT_REASON_HELPER.reason(code); } }
Get called contract address, name of contract, and function name. Decode the revert reason in the event one was returned. Internal function to ensure that protected functions can only be called from this contract and that they have the appropriate context set. The self-call context is then cleared. It is used as an additional guard against reentrancy, especially once generic actions are supported by the smart wallet in future versions. selfCallContext bytes4 The expected self-call context, equal to the function selector of the approved calling function./ Ensure caller is this contract and self-call context is correctly set.
(address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave bad data calling ", functionName, "." ) ) ); } (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); string memory revertReason = _decodeRevertReason(data); emit ExternalError( account, string( abi.encodePacked( name, " reverted calling ", functionName, ": ", revertReason ) ) ); } } function _enforceSelfCallFrom(bytes4 selfCallContext) internal { if (msg.sender != address(this) || _selfCallContext != selfCallContext) { revert(_revertReason(25)); } }
2,135,619
// SPDX-License-Identifier: MIT // 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 disstributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; // Finds new Curves! logs their addresses and provides `isCurve(address) -> (bool)` import "./Curve.sol"; import "./interfaces/IFreeFromUpTo.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract CurveFactory is Ownable { event NewCurve(address indexed caller, bytes32 indexed id, address indexed curve); mapping(bytes32 => address) public curves; function getCurve(address _baseCurrency, address _quoteCurrency) external view returns (address) { bytes32 curveId = keccak256(abi.encode(_baseCurrency, _quoteCurrency)); return (curves[curveId]); } function newCurve( string memory _name, string memory _symbol, address _baseCurrency, address _quoteCurrency, uint256 _baseWeight, uint256 _quoteWeight, address _baseAssimilator, address _quoteAssimilator ) public onlyOwner returns (Curve) { bytes32 curveId = keccak256(abi.encode(_baseCurrency, _quoteCurrency)); if (curves[curveId] != address(0)) revert("CurveFactory/currency-pair-already-exists"); address[] memory _assets = new address[](10); uint256[] memory _assetWeights = new uint256[](2); // Base Currency _assets[0] = _baseCurrency; _assets[1] = _baseAssimilator; _assets[2] = _baseCurrency; _assets[3] = _baseAssimilator; _assets[4] = _baseCurrency; // Quote Currency (typically USDC) _assets[5] = _quoteCurrency; _assets[6] = _quoteAssimilator; _assets[7] = _quoteCurrency; _assets[8] = _quoteAssimilator; _assets[9] = _quoteCurrency; // Weights _assetWeights[0] = _baseWeight; _assetWeights[1] = _quoteWeight; // New curve Curve curve = new Curve(_name, _symbol, _assets, _assetWeights); curve.transferOwnership(msg.sender); curves[curveId] = address(curve); emit NewCurve(msg.sender, curveId, address(curve)); return curve; } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "./lib/ABDKMath64x64.sol"; import "./Orchestrator.sol"; import "./ProportionalLiquidity.sol"; import "./Swaps.sol"; import "./ViewLiquidity.sol"; import "./Storage.sol"; import "./MerkleProver.sol"; import "./interfaces/IFreeFromUpTo.sol"; library Curves { using ABDKMath64x64 for int128; event Approval(address indexed _owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function add( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x + y) >= x, errorMessage); } function sub( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer( Storage.Curve storage curve, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve( Storage.Curve storage curve, address spender, uint256 amount ) external returns (bool) { _approve(curve, msg.sender, 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, sender, recipient, amount); _approve( curve, sender, msg.sender, sub(curve.allowances[sender][msg.sender], amount, "Curve/insufficient-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( Storage.Curve storage curve, address spender, uint256 addedValue ) external returns (bool) { _approve( curve, msg.sender, spender, add(curve.allowances[msg.sender][spender], addedValue, "Curve/approval-overflow") ); 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( Storage.Curve storage curve, address spender, uint256 subtractedValue ) external returns (bool) { _approve( curve, msg.sender, spender, sub(curve.allowances[msg.sender][spender], subtractedValue, "Curve/allowance-decrease-underflow") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is public 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); curve.balances[sender] = sub(curve.balances[sender], amount, "Curve/insufficient-balance"); curve.balances[recipient] = add(curve.balances[recipient], amount, "Curve/transfer-overflow"); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `_owner`s tokens. * * This is public 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( Storage.Curve storage curve, address _owner, address spender, uint256 amount ) private { require(_owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); curve.allowances[_owner][spender] = amount; emit Approval(_owner, spender, amount); } } contract Curve is Storage, MerkleProver { using SafeMath for uint256; event Approval(address indexed _owner, address indexed spender, uint256 value); event ParametersSet(uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda); event AssetIncluded(address indexed numeraire, address indexed reserve, uint256 weight); event AssimilatorIncluded( address indexed derivative, address indexed numeraire, address indexed reserve, address assimilator ); event PartitionRedeemed(address indexed token, address indexed redeemer, uint256 value); event OwnershipTransfered(address indexed previousOwner, address indexed newOwner); event FrozenSet(bool isFrozen); event EmergencyAlarm(bool isEmergency); event WhitelistingStopped(); event Trade( address indexed trader, address indexed origin, address indexed target, uint256 originAmount, uint256 targetAmount ); event Transfer(address indexed from, address indexed to, uint256 value); modifier onlyOwner() { require(msg.sender == owner, "Curve/caller-is-not-owner"); _; } modifier nonReentrant() { require(notEntered, "Curve/re-entered"); notEntered = false; _; notEntered = true; } modifier transactable() { require(!frozen, "Curve/frozen-only-allowing-proportional-withdraw"); _; } modifier isEmergency() { require(emergency, "Curve/emergency-only-allowing-emergency-proportional-withdraw"); _; } modifier deadline(uint256 _deadline) { require(block.timestamp < _deadline, "Curve/tx-deadline-passed"); _; } modifier inWhitelistingStage() { require(whitelistingStage, "Curve/whitelist-stage-on-going"); _; } modifier notInWhitelistingStage() { require(!whitelistingStage, "Curve/whitelist-stage-stopped"); _; } modifier underCap(uint256 amount) { ( uint256 total_, ) = liquidity(); require(curve.cap == 0 || curve.cap > amount.add(total_), "Curve/amount-too-large"); _; } constructor( string memory _name, string memory _symbol, address[] memory _assets, uint256[] memory _assetWeights ) { owner = msg.sender; name = _name; symbol = _symbol; emit OwnershipTransfered(address(0), msg.sender); Orchestrator.initialize(curve, numeraires, reserves, derivatives, _assets, _assetWeights); } /// @notice sets the parameters for the pool /// @param _alpha the value for alpha (halt threshold) must be less than or equal to 1 and greater than 0 /// @param _beta the value for beta must be less than alpha and greater than 0 /// @param _feeAtHalt the maximum value for the fee at the halt point /// @param _epsilon the base fee for the pool /// @param _lambda the value for lambda must be less than or equal to 1 and greater than zero function setParams( uint256 _alpha, uint256 _beta, uint256 _feeAtHalt, uint256 _epsilon, uint256 _lambda ) external onlyOwner { Orchestrator.setParams(curve, _alpha, _beta, _feeAtHalt, _epsilon, _lambda); } /// @notice excludes an assimilator from the curve /// @param _derivative the address of the assimilator to exclude function excludeDerivative(address _derivative) external onlyOwner { for (uint256 i = 0; i < numeraires.length; i++) { if (_derivative == numeraires[i]) revert("Curve/cannot-delete-numeraire"); if (_derivative == reserves[i]) revert("Curve/cannot-delete-reserve"); } delete curve.assimilators[_derivative]; } /// @notice view the current parameters of the curve /// @return alpha_ the current alpha value /// beta_ the current beta value /// delta_ the current delta value /// epsilon_ the current epsilon value /// lambda_ the current lambda value /// omega_ the current omega value function viewCurve() external view returns ( uint256 alpha_, uint256 beta_, uint256 delta_, uint256 epsilon_, uint256 lambda_ ) { return Orchestrator.viewCurve(curve); } function turnOffWhitelisting() external onlyOwner { emit WhitelistingStopped(); whitelistingStage = false; } function setEmergency(bool _emergency) external onlyOwner { emit EmergencyAlarm(_emergency); emergency = _emergency; } function setFrozen(bool _toFreezeOrNotToFreeze) external onlyOwner { emit FrozenSet(_toFreezeOrNotToFreeze); frozen = _toFreezeOrNotToFreeze; } function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Curve/new-owner-cannot-be-zeroth-address"); emit OwnershipTransfered(owner, _newOwner); owner = _newOwner; } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @param _minTargetAmount the minimum target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return targetAmount_ the amount of target that has been swapped for the origin amount function originSwap( address _origin, address _target, uint256 _originAmount, uint256 _minTargetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 targetAmount_) { targetAmount_ = Swaps.originSwap(curve, _origin, _target, _originAmount, msg.sender); require(targetAmount_ >= _minTargetAmount, "Curve/below-min-target-amount"); } /// @notice view how much target amount a fixed origin amount will swap for /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @return targetAmount_ the target amount that would have been swapped for the origin amount function viewOriginSwap( address _origin, address _target, uint256 _originAmount ) external view transactable returns (uint256 targetAmount_) { targetAmount_ = Swaps.viewOriginSwap(curve, _origin, _target, _originAmount); } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _maxOriginAmount the maximum origin amount /// @param _targetAmount the target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return originAmount_ the amount of origin that has been swapped for the target function targetSwap( address _origin, address _target, uint256 _maxOriginAmount, uint256 _targetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 originAmount_) { originAmount_ = Swaps.targetSwap(curve, _origin, _target, _targetAmount, msg.sender); require(originAmount_ <= _maxOriginAmount, "Curve/above-max-origin-amount"); } /// @notice view how much of the origin currency the target currency will take /// @param _origin the address of the origin /// @param _target the address of the target /// @param _targetAmount the target amount /// @return originAmount_ the amount of target that has been swapped for the origin function viewTargetSwap( address _origin, address _target, uint256 _targetAmount ) external view transactable returns (uint256 originAmount_) { originAmount_ = Swaps.viewTargetSwap(curve, _origin, _target, _targetAmount); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param index Index corresponding to the merkleProof /// @param account Address coorresponding to the merkleProof /// @param amount Amount coorresponding to the merkleProof, should always be 1 /// @param merkleProof Merkle proof /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function depositWithWhitelist( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 _deposit, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant inWhitelistingStage returns (uint256, uint256[] memory) { require(isWhitelisted(index, account, amount, merkleProof), "Curve/not-whitelisted"); require(msg.sender == account, "Curve/not-approved-user"); (uint256 curvesMinted_, uint256[] memory deposits_) = ProportionalLiquidity.proportionalDeposit(curve, _deposit); whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].add(curvesMinted_); // 10k max deposit if (whitelistedDeposited[msg.sender] > 10000e18) { revert("Curve/exceed-whitelist-maximum-deposit"); } return (curvesMinted_, deposits_); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function deposit(uint256 _deposit, uint256 _deadline) external deadline(_deadline) transactable nonReentrant notInWhitelistingStage underCap(_deposit) returns (uint256, uint256[] memory) { return ProportionalLiquidity.proportionalDeposit(curve, _deposit); } /// @notice view deposits and curves minted a given deposit would return /// @param _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the /// prevailing proportions of the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function viewDeposit(uint256 _deposit) external view transactable underCap(_deposit) returns (uint256, uint256[] memory) { // curvesToMint_, depositsToMake_ return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit); } /// @notice Emergency withdraw tokens in the event that the oracle somehow bugs out /// and no one is able to withdraw due to the invariant check /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function emergencyWithdraw(uint256 _curvesToBurn, uint256 _deadline) external isEmergency deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { return ProportionalLiquidity.emergencyProportionalWithdraw(curve, _curvesToBurn); } /// @notice withdrawas amount of curve tokens from the the pool equally from the numeraire assets of the pool with no slippage /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function withdraw(uint256 _curvesToBurn, uint256 _deadline) external deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { if (whitelistingStage) { whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].sub(_curvesToBurn); } return ProportionalLiquidity.proportionalWithdraw(curve, _curvesToBurn); } /// @notice views the withdrawal information from the pool /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return the amonnts of numeraire assets withdrawn from the pool function viewWithdraw(uint256 _curvesToBurn) external view transactable returns (uint256[] memory) { return ProportionalLiquidity.viewProportionalWithdraw(curve, _curvesToBurn); } function supportsInterface(bytes4 _interface) public pure returns (bool supports_) { supports_ = this.supportsInterface.selector == _interface || // erc165 bytes4(0x7f5828d0) == _interface || // eip173 bytes4(0x36372b07) == _interface; // erc20 } /// @notice transfers curve tokens /// @param _recipient the address of where to send the curve tokens /// @param _amount the amount of curve tokens to send /// @return success_ the success bool of the call function transfer(address _recipient, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.transfer(curve, _recipient, _amount); } /// @notice transfers curve tokens from one address to another address /// @param _sender the account from which the curve tokens will be sent /// @param _recipient the account to which the curve tokens will be sent /// @param _amount the amount of curve tokens to transfer /// @return success_ the success bool of the call function transferFrom( address _sender, address _recipient, uint256 _amount ) public nonReentrant returns (bool success_) { success_ = Curves.transferFrom(curve, _sender, _recipient, _amount); } /// @notice approves a user to spend curve tokens on their behalf /// @param _spender the account to allow to spend from msg.sender /// @param _amount the amount to specify the spender can spend /// @return success_ the success bool of this call function approve(address _spender, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.approve(curve, _spender, _amount); } /// @notice view the curve token balance of a given account /// @param _account the account to view the balance of /// @return balance_ the curve token ballance of the given account function balanceOf(address _account) public view returns (uint256 balance_) { balance_ = curve.balances[_account]; } /// @notice views the total curve supply of the pool /// @return totalSupply_ the total supply of curve tokens function totalSupply() public view returns (uint256 totalSupply_) { totalSupply_ = curve.totalSupply; } /// @notice views the total allowance one address has to spend from another address /// @param _owner the address of the owner /// @param _spender the address of the spender /// @return allowance_ the amount the owner has allotted the spender function allowance(address _owner, address _spender) public view returns (uint256 allowance_) { allowance_ = curve.allowances[_owner][_spender]; } /// @notice views the total amount of liquidity in the curve in numeraire value and format - 18 decimals /// @return total_ the total value in the curve /// @return individual_ the individual values in the curve function liquidity() public view returns (uint256 total_, uint256[] memory individual_) { return ViewLiquidity.viewLiquidity(curve); } /// @notice view the assimilator address for a derivative /// @return assimilator_ the assimilator address function assimilator(address _derivative) public view returns (address assimilator_) { assimilator_ = curve.assimilators[_derivative].addr; } function setCap(uint256 _cap) public onlyOwner { require(_cap != curve.cap, "Curve/cap is already set"); curve.cap = _cap; emit CapChanged(_cap); } event CapChanged(uint256 _cap); } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IFreeFromUpTo { function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 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; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256 (xe); else x <<= uint256 (-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= uint256 (re); else if (re < 0) result >>= uint256 (-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./lib/ABDKMath64x64.sol"; import "./Storage.sol"; import "./CurveMath.sol"; library Orchestrator { using SafeERC20 for IERC20; using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; int128 private constant ONE_WEI = 0x12; event ParametersSet(uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda); event AssetIncluded(address indexed numeraire, address indexed reserve, uint256 weight); event AssimilatorIncluded( address indexed derivative, address indexed numeraire, address indexed reserve, address assimilator ); function setParams( Storage.Curve storage curve, uint256 _alpha, uint256 _beta, uint256 _feeAtHalt, uint256 _epsilon, uint256 _lambda ) external { require(0 < _alpha && _alpha < 1e18, "Curve/parameter-invalid-alpha"); require(_beta < _alpha, "Curve/parameter-invalid-beta"); require(_feeAtHalt <= 5e17, "Curve/parameter-invalid-max"); require(_epsilon <= 1e16, "Curve/parameter-invalid-epsilon"); require(_lambda <= 1e18, "Curve/parameter-invalid-lambda"); int128 _omega = getFee(curve); curve.alpha = (_alpha + 1).divu(1e18); curve.beta = (_beta + 1).divu(1e18); curve.delta = (_feeAtHalt).divu(1e18).div(uint256(2).fromUInt().mul(curve.alpha.sub(curve.beta))) + ONE_WEI; curve.epsilon = (_epsilon + 1).divu(1e18); curve.lambda = (_lambda + 1).divu(1e18); int128 _psi = getFee(curve); require(_omega >= _psi, "Curve/parameters-increase-fee"); emit ParametersSet(_alpha, _beta, curve.delta.mulu(1e18), _epsilon, _lambda); } function getFee(Storage.Curve storage curve) private view returns (int128 fee_) { int128 _gLiq; // Always pairs int128[] memory _bals = new int128[](2); for (uint256 i = 0; i < _bals.length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(curve.assets[i].addr); _bals[i] = _bal; _gLiq += _bal; } fee_ = CurveMath.calculateFee(_gLiq, _bals, curve.beta, curve.delta, curve.weights); } function initialize( Storage.Curve storage curve, address[] storage numeraires, address[] storage reserves, address[] storage derivatives, address[] calldata _assets, uint256[] calldata _assetWeights ) external { require(_assetWeights.length == 2, "Curve/assetWeights-must-be-length-two"); require(_assets.length % 5 == 0, "Curve/assets-must-be-divisible-by-five"); for (uint256 i = 0; i < _assetWeights.length; i++) { uint256 ix = i * 5; numeraires.push(_assets[ix]); derivatives.push(_assets[ix]); reserves.push(_assets[2 + ix]); if (_assets[ix] != _assets[2 + ix]) derivatives.push(_assets[2 + ix]); includeAsset( curve, _assets[ix], // numeraire _assets[1 + ix], // numeraire assimilator _assets[2 + ix], // reserve _assets[3 + ix], // reserve assimilator _assets[4 + ix], // reserve approve to _assetWeights[i] ); } } function includeAsset( Storage.Curve storage curve, address _numeraire, address _numeraireAssim, address _reserve, address _reserveAssim, address _reserveApproveTo, uint256 _weight ) private { require(_numeraire != address(0), "Curve/numeraire-cannot-be-zeroth-address"); require(_numeraireAssim != address(0), "Curve/numeraire-assimilator-cannot-be-zeroth-address"); require(_reserve != address(0), "Curve/reserve-cannot-be-zeroth-address"); require(_reserveAssim != address(0), "Curve/reserve-assimilator-cannot-be-zeroth-address"); require(_weight < 1e18, "Curve/weight-must-be-less-than-one"); if (_numeraire != _reserve) IERC20(_numeraire).safeApprove(_reserveApproveTo, uint256(-1)); Storage.Assimilator storage _numeraireAssimilator = curve.assimilators[_numeraire]; _numeraireAssimilator.addr = _numeraireAssim; _numeraireAssimilator.ix = uint8(curve.assets.length); Storage.Assimilator storage _reserveAssimilator = curve.assimilators[_reserve]; _reserveAssimilator.addr = _reserveAssim; _reserveAssimilator.ix = uint8(curve.assets.length); int128 __weight = _weight.divu(1e18).add(uint256(1).divu(1e18)); curve.weights.push(__weight); curve.assets.push(_numeraireAssimilator); emit AssetIncluded(_numeraire, _reserve, _weight); emit AssimilatorIncluded(_numeraire, _numeraire, _reserve, _numeraireAssim); if (_numeraireAssim != _reserveAssim) { emit AssimilatorIncluded(_reserve, _numeraire, _reserve, _reserveAssim); } } function includeAssimilator( Storage.Curve storage curve, address _derivative, address _numeraire, address _reserve, address _assimilator, address _derivativeApproveTo ) private { require(_derivative != address(0), "Curve/derivative-cannot-be-zeroth-address"); require(_numeraire != address(0), "Curve/numeraire-cannot-be-zeroth-address"); require(_reserve != address(0), "Curve/numeraire-cannot-be-zeroth-address"); require(_assimilator != address(0), "Curve/assimilator-cannot-be-zeroth-address"); IERC20(_numeraire).safeApprove(_derivativeApproveTo, uint256(-1)); Storage.Assimilator storage _numeraireAssim = curve.assimilators[_numeraire]; curve.assimilators[_derivative] = Storage.Assimilator(_assimilator, _numeraireAssim.ix); emit AssimilatorIncluded(_derivative, _numeraire, _reserve, _assimilator); } function viewCurve(Storage.Curve storage curve) external view returns ( uint256 alpha_, uint256 beta_, uint256 delta_, uint256 epsilon_, uint256 lambda_ ) { alpha_ = curve.alpha.mulu(1e18); beta_ = curve.beta.mulu(1e18); delta_ = curve.delta.mulu(1e18); epsilon_ = curve.epsilon.mulu(1e18); lambda_ = curve.lambda.mulu(1e18); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./Assimilators.sol"; import "./Storage.sol"; import "./lib/UnsafeMath64x64.sol"; import "./lib/ABDKMath64x64.sol"; import "./CurveMath.sol"; library ProportionalLiquidity { using ABDKMath64x64 for uint256; using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; event Transfer(address indexed from, address indexed to, uint256 value); int128 public constant ONE = 0x10000000000000000; int128 public constant ONE_WEI = 0x12; function proportionalDeposit(Storage.Curve storage curve, uint256 _deposit) external returns (uint256 curves_, uint256[] memory) { int128 __deposit = _deposit.divu(1e18); uint256 _length = curve.assets.length; uint256[] memory deposits_ = new uint256[](_length); (int128 _oGLiq, int128[] memory _oBals) = getGrossLiquidityAndBalancesForDeposit(curve); // Needed to calculate liquidity invariant (int128 _oGLiqProp, int128[] memory _oBalsProp) = getGrossLiquidityAndBalances(curve); // No liquidity, oracle sets the ratio if (_oGLiq == 0) { for (uint256 i = 0; i < _length; i++) { // Variable here to avoid stack-too-deep errors int128 _d = __deposit.mul(curve.weights[i]); deposits_[i] = Assimilators.intakeNumeraire(curve.assets[i].addr, _d.add(ONE_WEI)); } } else { // We already have an existing pool ratio // which must be respected int128 _multiplier = __deposit.div(_oGLiq); uint256 _baseWeight = curve.weights[0].mulu(1e18); uint256 _quoteWeight = curve.weights[1].mulu(1e18); for (uint256 i = 0; i < _length; i++) { deposits_[i] = Assimilators.intakeNumeraireLPRatio( curve.assets[i].addr, _baseWeight, _quoteWeight, _oBals[i].mul(_multiplier).add(ONE_WEI) ); } } int128 _totalShells = curve.totalSupply.divu(1e18); int128 _newShells = __deposit; if (_totalShells > 0) { _newShells = __deposit.div(_oGLiq); _newShells = _newShells.mul(_totalShells); } requireLiquidityInvariant(curve, _totalShells, _newShells, _oGLiqProp, _oBalsProp); mint(curve, msg.sender, curves_ = _newShells.mulu(1e18)); return (curves_, deposits_); } function viewProportionalDeposit(Storage.Curve storage curve, uint256 _deposit) external view returns (uint256 curves_, uint256[] memory) { int128 __deposit = _deposit.divu(1e18); uint256 _length = curve.assets.length; (int128 _oGLiq, int128[] memory _oBals) = getGrossLiquidityAndBalancesForDeposit(curve); uint256[] memory deposits_ = new uint256[](_length); // No liquidity if (_oGLiq == 0) { for (uint256 i = 0; i < _length; i++) { deposits_[i] = Assimilators.viewRawAmount( curve.assets[i].addr, __deposit.mul(curve.weights[i]).add(ONE_WEI) ); } } else { // We already have an existing pool ratio // this must be respected int128 _multiplier = __deposit.div(_oGLiq); uint256 _baseWeight = curve.weights[0].mulu(1e18); uint256 _quoteWeight = curve.weights[1].mulu(1e18); // Deposits into the pool is determined by existing LP ratio for (uint256 i = 0; i < _length; i++) { deposits_[i] = Assimilators.viewRawAmountLPRatio( curve.assets[i].addr, _baseWeight, _quoteWeight, _oBals[i].mul(_multiplier).add(ONE_WEI) ); } } int128 _totalShells = curve.totalSupply.divu(1e18); int128 _newShells = __deposit; if (_totalShells > 0) { _newShells = __deposit.div(_oGLiq); _newShells = _newShells.mul(_totalShells); } curves_ = _newShells.mulu(1e18); return (curves_, deposits_); } function emergencyProportionalWithdraw(Storage.Curve storage curve, uint256 _withdrawal) external returns (uint256[] memory) { uint256 _length = curve.assets.length; (, int128[] memory _oBals) = getGrossLiquidityAndBalances(curve); uint256[] memory withdrawals_ = new uint256[](_length); int128 _totalShells = curve.totalSupply.divu(1e18); int128 __withdrawal = _withdrawal.divu(1e18); int128 _multiplier = __withdrawal.div(_totalShells); for (uint256 i = 0; i < _length; i++) { withdrawals_[i] = Assimilators.outputNumeraire( curve.assets[i].addr, msg.sender, _oBals[i].mul(_multiplier) ); } burn(curve, msg.sender, _withdrawal); return withdrawals_; } function proportionalWithdraw(Storage.Curve storage curve, uint256 _withdrawal) external returns (uint256[] memory) { uint256 _length = curve.assets.length; (int128 _oGLiq, int128[] memory _oBals) = getGrossLiquidityAndBalances(curve); uint256[] memory withdrawals_ = new uint256[](_length); int128 _totalShells = curve.totalSupply.divu(1e18); int128 __withdrawal = _withdrawal.divu(1e18); int128 _multiplier = __withdrawal.div(_totalShells); for (uint256 i = 0; i < _length; i++) { withdrawals_[i] = Assimilators.outputNumeraire( curve.assets[i].addr, msg.sender, _oBals[i].mul(_multiplier) ); } requireLiquidityInvariant(curve, _totalShells, __withdrawal.neg(), _oGLiq, _oBals); burn(curve, msg.sender, _withdrawal); return withdrawals_; } function viewProportionalWithdraw(Storage.Curve storage curve, uint256 _withdrawal) external view returns (uint256[] memory) { uint256 _length = curve.assets.length; (, int128[] memory _oBals) = getGrossLiquidityAndBalances(curve); uint256[] memory withdrawals_ = new uint256[](_length); int128 _multiplier = _withdrawal.divu(1e18).div(curve.totalSupply.divu(1e18)); for (uint256 i = 0; i < _length; i++) { withdrawals_[i] = Assimilators.viewRawAmount(curve.assets[i].addr, _oBals[i].mul(_multiplier)); } return withdrawals_; } function getGrossLiquidityAndBalancesForDeposit(Storage.Curve storage curve) internal view returns (int128 grossLiquidity_, int128[] memory) { uint256 _length = curve.assets.length; int128[] memory balances_ = new int128[](_length); uint256 _baseWeight = curve.weights[0].mulu(1e18); uint256 _quoteWeight = curve.weights[1].mulu(1e18); for (uint256 i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalanceLPRatio(_baseWeight, _quoteWeight, curve.assets[i].addr); balances_[i] = _bal; grossLiquidity_ += _bal; } return (grossLiquidity_, balances_); } function getGrossLiquidityAndBalances(Storage.Curve storage curve) internal view returns (int128 grossLiquidity_, int128[] memory) { uint256 _length = curve.assets.length; int128[] memory balances_ = new int128[](_length); for (uint256 i = 0; i < _length; i++) { int128 _bal = Assimilators.viewNumeraireBalance(curve.assets[i].addr); balances_[i] = _bal; grossLiquidity_ += _bal; } return (grossLiquidity_, balances_); } function requireLiquidityInvariant( Storage.Curve storage curve, int128 _curves, int128 _newShells, int128 _oGLiq, int128[] memory _oBals ) private view { (int128 _nGLiq, int128[] memory _nBals) = getGrossLiquidityAndBalances(curve); int128 _beta = curve.beta; int128 _delta = curve.delta; int128[] memory _weights = curve.weights; int128 _omega = CurveMath.calculateFee(_oGLiq, _oBals, _beta, _delta, _weights); int128 _psi = CurveMath.calculateFee(_nGLiq, _nBals, _beta, _delta, _weights); CurveMath.enforceLiquidityInvariant(_curves, _newShells, _oGLiq, _nGLiq, _omega, _psi); } function burn( Storage.Curve storage curve, address account, uint256 amount ) private { curve.balances[account] = burnSub(curve.balances[account], amount); curve.totalSupply = burnSub(curve.totalSupply, amount); emit Transfer(msg.sender, address(0), amount); } function mint( Storage.Curve storage curve, address account, uint256 amount ) private { curve.totalSupply = mintAdd(curve.totalSupply, amount); curve.balances[account] = mintAdd(curve.balances[account], amount); emit Transfer(address(0), msg.sender, amount); } function mintAdd(uint256 x, uint256 y) private pure returns (uint256 z) { require((z = x + y) >= x, "Curve/mint-overflow"); } function burnSub(uint256 x, uint256 y) private pure returns (uint256 z) { require((z = x - y) <= x, "Curve/burn-underflow"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "./Assimilators.sol"; import "./Storage.sol"; import "./CurveMath.sol"; import "./lib/UnsafeMath64x64.sol"; import "./lib/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Swaps { using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; using ABDKMath64x64 for uint256; using SafeMath for uint256; event Trade( address indexed trader, address indexed origin, address indexed target, uint256 originAmount, uint256 targetAmount ); int128 public constant ONE = 0x10000000000000000; function getOriginAndTarget( Storage.Curve storage curve, address _o, address _t ) private view returns (Storage.Assimilator memory, Storage.Assimilator memory) { Storage.Assimilator memory o_ = curve.assimilators[_o]; Storage.Assimilator memory t_ = curve.assimilators[_t]; require(o_.addr != address(0), "Curve/origin-not-supported"); require(t_.addr != address(0), "Curve/target-not-supported"); return (o_, t_); } function originSwap( Storage.Curve storage curve, address _origin, address _target, uint256 _originAmount, address _recipient ) external returns (uint256 tAmt_) { (Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target); if (_o.ix == _t.ix) return Assimilators.outputNumeraire(_t.addr, _recipient, Assimilators.intakeRaw(_o.addr, _originAmount)); (int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals) = getOriginSwapData(curve, _o.ix, _t.ix, _o.addr, _originAmount); _amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _t.ix); _amt = _amt.us_mul(ONE - curve.epsilon); tAmt_ = Assimilators.outputNumeraire(_t.addr, _recipient, _amt); emit Trade(msg.sender, _origin, _target, _originAmount, tAmt_); } function viewOriginSwap( Storage.Curve storage curve, address _origin, address _target, uint256 _originAmount ) external view returns (uint256 tAmt_) { (Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target); if (_o.ix == _t.ix) return Assimilators.viewRawAmount(_t.addr, Assimilators.viewNumeraireAmount(_o.addr, _originAmount)); (int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _nBals, int128[] memory _oBals) = viewOriginSwapData(curve, _o.ix, _t.ix, _originAmount, _o.addr); _amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _t.ix); _amt = _amt.us_mul(ONE - curve.epsilon); tAmt_ = Assimilators.viewRawAmount(_t.addr, _amt.abs()); } function targetSwap( Storage.Curve storage curve, address _origin, address _target, uint256 _targetAmount, address _recipient ) external returns (uint256 oAmt_) { (Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target); if (_o.ix == _t.ix) return Assimilators.intakeNumeraire(_o.addr, Assimilators.outputRaw(_t.addr, _recipient, _targetAmount)); // If the origin is the quote currency (i.e. usdc) // we need to make sure to massage the _targetAmount // by dividing it by the exchange rate (so it gets // multiplied later to reach the same target amount). // Inelegant solution, but this way we don't need to // re-write large chunks of the code-base // curve.assets[1].addr = quoteCurrency // no variable assignment due to stack too deep if (curve.assets[1].addr == _o.addr) { _targetAmount = _targetAmount.mul(1e8).div(Assimilators.getRate(_t.addr)); } (int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals) = getTargetSwapData(curve, _t.ix, _o.ix, _t.addr, _recipient, _targetAmount); _amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _o.ix); // If the origin is the quote currency (i.e. usdc) // we need to make sure to massage the _amt too // curve.assets[1].addr = quoteCurrency if (curve.assets[1].addr == _o.addr) { _amt = _amt.mul(Assimilators.getRate(_t.addr).divu(1e8)); } _amt = _amt.us_mul(ONE + curve.epsilon); oAmt_ = Assimilators.intakeNumeraire(_o.addr, _amt); emit Trade(msg.sender, _origin, _target, oAmt_, _targetAmount); } function viewTargetSwap( Storage.Curve storage curve, address _origin, address _target, uint256 _targetAmount ) external view returns (uint256 oAmt_) { (Storage.Assimilator memory _o, Storage.Assimilator memory _t) = getOriginAndTarget(curve, _origin, _target); if (_o.ix == _t.ix) return Assimilators.viewRawAmount(_o.addr, Assimilators.viewNumeraireAmount(_t.addr, _targetAmount)); // If the origin is the quote currency (i.e. usdc) // we need to make sure to massage the _targetAmount // by dividing it by the exchange rate (so it gets // multiplied later to reach the same target amount). // Inelegant solution, but this way we don't need to // re-write large chunks of the code-base // curve.assets[1].addr = quoteCurrency // no variable assignment due to stack too deep if (curve.assets[1].addr == _o.addr) { _targetAmount = _targetAmount.mul(1e8).div(Assimilators.getRate(_t.addr)); } (int128 _amt, int128 _oGLiq, int128 _nGLiq, int128[] memory _nBals, int128[] memory _oBals) = viewTargetSwapData(curve, _t.ix, _o.ix, _targetAmount, _t.addr); _amt = CurveMath.calculateTrade(curve, _oGLiq, _nGLiq, _oBals, _nBals, _amt, _o.ix); // If the origin is the quote currency (i.e. usdc) // we need to make sure to massage the _amt too // curve.assets[1].addr = quoteCurrency if (curve.assets[1].addr == _o.addr) { _amt = _amt.mul(Assimilators.getRate(_t.addr).divu(1e8)); } _amt = _amt.us_mul(ONE + curve.epsilon); oAmt_ = Assimilators.viewRawAmount(_o.addr, _amt); } function getOriginSwapData( Storage.Curve storage curve, uint256 _inputIx, uint256 _outputIx, address _assim, uint256 _amt ) private returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint256 _length = curve.assets.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); Storage.Assimilator[] memory _reserves = curve.assets; for (uint256 i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(_reserves[i].addr); else { int128 _bal; (amt_, _bal) = Assimilators.intakeRawAndGetBalance(_assim, _amt); oBals_[i] = _bal.sub(amt_); nBals_[i] = _bal; } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_); return (amt_, oGLiq_, nGLiq_, oBals_, nBals_); } function getTargetSwapData( Storage.Curve storage curve, uint256 _inputIx, uint256 _outputIx, address _assim, address _recipient, uint256 _amt ) private returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint256 _length = curve.assets.length; int128[] memory oBals_ = new int128[](_length); int128[] memory nBals_ = new int128[](_length); Storage.Assimilator[] memory _reserves = curve.assets; for (uint256 i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(_reserves[i].addr); else { int128 _bal; (amt_, _bal) = Assimilators.outputRawAndGetBalance(_assim, _recipient, _amt); oBals_[i] = _bal.sub(amt_); nBals_[i] = _bal; } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_); return (amt_, oGLiq_, nGLiq_, oBals_, nBals_); } function viewOriginSwapData( Storage.Curve storage curve, uint256 _inputIx, uint256 _outputIx, uint256 _amt, address _assim ) private view returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint256 _length = curve.assets.length; int128[] memory nBals_ = new int128[](_length); int128[] memory oBals_ = new int128[](_length); for (uint256 i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(curve.assets[i].addr); else { int128 _bal; (amt_, _bal) = Assimilators.viewNumeraireAmountAndBalance(_assim, _amt); oBals_[i] = _bal; nBals_[i] = _bal.add(amt_); } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_); return (amt_, oGLiq_, nGLiq_, nBals_, oBals_); } function viewTargetSwapData( Storage.Curve storage curve, uint256 _inputIx, uint256 _outputIx, uint256 _amt, address _assim ) private view returns ( int128 amt_, int128 oGLiq_, int128 nGLiq_, int128[] memory, int128[] memory ) { uint256 _length = curve.assets.length; int128[] memory nBals_ = new int128[](_length); int128[] memory oBals_ = new int128[](_length); for (uint256 i = 0; i < _length; i++) { if (i != _inputIx) nBals_[i] = oBals_[i] = Assimilators.viewNumeraireBalance(curve.assets[i].addr); else { int128 _bal; (amt_, _bal) = Assimilators.viewNumeraireAmountAndBalance(_assim, _amt); amt_ = amt_.neg(); oBals_[i] = _bal; nBals_[i] = _bal.add(amt_); } oGLiq_ += oBals_[i]; nGLiq_ += nBals_[i]; } nGLiq_ = nGLiq_.sub(amt_); nBals_[_outputIx] = ABDKMath64x64.sub(nBals_[_outputIx], amt_); return (amt_, oGLiq_, nGLiq_, nBals_, oBals_); } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "./Storage.sol"; import "./Assimilators.sol"; import "./lib/ABDKMath64x64.sol"; library ViewLiquidity { using ABDKMath64x64 for int128; function viewLiquidity(Storage.Curve storage curve) external view returns (uint256 total_, uint256[] memory individual_) { uint256 _length = curve.assets.length; individual_ = new uint256[](_length); for (uint256 i = 0; i < _length; i++) { uint256 _liquidity = Assimilators.viewNumeraireBalance(curve.assets[i].addr).mulu(1e18); total_ += _liquidity; individual_[i] = _liquidity; } return (total_, individual_); } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "./interfaces/IOracle.sol"; import "./Assimilators.sol"; contract Storage { struct Curve { // Curve parameters int128 alpha; int128 beta; int128 delta; int128 epsilon; int128 lambda; int128[] weights; uint256 cap; // Assets and their assimilators Assimilator[] assets; mapping(address => Assimilator) assimilators; // Oracles to determine the price // Note that 0'th index should always be USDC 1e18 // Oracle's pricing should be denominated in Currency/USDC mapping(address => IOracle) oracles; // ERC20 Interface uint256 totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowances; } struct Assimilator { address addr; uint8 ix; } // Curve parameters Curve public curve; // Ownable address public owner; string public name; string public symbol; uint8 public constant decimals = 18; address[] public derivatives; address[] public numeraires; address[] public reserves; // Curve operational state bool public frozen = false; bool public emergency = false; bool public whitelistingStage = true; bool internal notEntered = true; mapping(address => uint256) public whitelistedDeposited; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; contract MerkleProver { bytes32 public immutable merkleRoot = bytes32(0xf4dbd0fb1957570029a847490cb3d731a45962072953ba7da80ff132ccd97d51); function isWhitelisted( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) public view returns (bool) { // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); return MerkleProof.verify(merkleProof, merkleRoot, node); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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; 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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "./Storage.sol"; import "./lib/UnsafeMath64x64.sol"; import "./lib/ABDKMath64x64.sol"; library CurveMath { int128 private constant ONE = 0x10000000000000000; int128 private constant MAX = 0x4000000000000000; // .25 in layman's terms int128 private constant MAX_DIFF = -0x10C6F7A0B5EE; int128 private constant ONE_WEI = 0x12; using ABDKMath64x64 for int128; using UnsafeMath64x64 for int128; using ABDKMath64x64 for uint256; // This is used to prevent stack too deep errors function calculateFee( int128 _gLiq, int128[] memory _bals, Storage.Curve storage curve, int128[] memory _weights ) internal view returns (int128 psi_) { int128 _beta = curve.beta; int128 _delta = curve.delta; psi_ = calculateFee(_gLiq, _bals, _beta, _delta, _weights); } function calculateFee( int128 _gLiq, int128[] memory _bals, int128 _beta, int128 _delta, int128[] memory _weights ) internal pure returns (int128 psi_) { uint256 _length = _bals.length; for (uint256 i = 0; i < _length; i++) { int128 _ideal = _gLiq.mul(_weights[i]); psi_ += calculateMicroFee(_bals[i], _ideal, _beta, _delta); } } function calculateMicroFee( int128 _bal, int128 _ideal, int128 _beta, int128 _delta ) private pure returns (int128 fee_) { if (_bal < _ideal) { int128 _threshold = _ideal.mul(ONE - _beta); if (_bal < _threshold) { int128 _feeMargin = _threshold - _bal; fee_ = _feeMargin.div(_ideal); fee_ = fee_.mul(_delta); if (fee_ > MAX) fee_ = MAX; fee_ = fee_.mul(_feeMargin); } else fee_ = 0; } else { int128 _threshold = _ideal.mul(ONE + _beta); if (_bal > _threshold) { int128 _feeMargin = _bal - _threshold; fee_ = _feeMargin.div(_ideal); fee_ = fee_.mul(_delta); if (fee_ > MAX) fee_ = MAX; fee_ = fee_.mul(_feeMargin); } else fee_ = 0; } } function calculateTrade( Storage.Curve storage curve, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals, int128 _inputAmt, uint256 _outputIndex ) internal view returns (int128 outputAmt_) { outputAmt_ = -_inputAmt; int128 _lambda = curve.lambda; int128[] memory _weights = curve.weights; int128 _omega = calculateFee(_oGLiq, _oBals, curve, _weights); int128 _psi; for (uint256 i = 0; i < 32; i++) { _psi = calculateFee(_nGLiq, _nBals, curve, _weights); int128 prevAmount; { prevAmount = outputAmt_; outputAmt_ = _omega < _psi ? -(_inputAmt + _omega - _psi) : -(_inputAmt + _lambda.mul(_omega - _psi)); } if (outputAmt_ / 1e13 == prevAmount / 1e13) { _nGLiq = _oGLiq + _inputAmt + outputAmt_; _nBals[_outputIndex] = _oBals[_outputIndex] + outputAmt_; enforceHalts(curve, _oGLiq, _nGLiq, _oBals, _nBals, _weights); enforceSwapInvariant(_oGLiq, _omega, _nGLiq, _psi); return outputAmt_; } else { _nGLiq = _oGLiq + _inputAmt + outputAmt_; _nBals[_outputIndex] = _oBals[_outputIndex].add(outputAmt_); } } revert("Curve/swap-convergence-failed"); } function calculateLiquidityMembrane( Storage.Curve storage curve, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals ) internal view returns (int128 curves_) { enforceHalts(curve, _oGLiq, _nGLiq, _oBals, _nBals, curve.weights); int128 _omega; int128 _psi; { int128 _beta = curve.beta; int128 _delta = curve.delta; int128[] memory _weights = curve.weights; _omega = calculateFee(_oGLiq, _oBals, _beta, _delta, _weights); _psi = calculateFee(_nGLiq, _nBals, _beta, _delta, _weights); } int128 _feeDiff = _psi.sub(_omega); int128 _liqDiff = _nGLiq.sub(_oGLiq); int128 _oUtil = _oGLiq.sub(_omega); int128 _totalShells = curve.totalSupply.divu(1e18); int128 _curveMultiplier; if (_totalShells == 0) { curves_ = _nGLiq.sub(_psi); } else if (_feeDiff >= 0) { _curveMultiplier = _liqDiff.sub(_feeDiff).div(_oUtil); } else { _curveMultiplier = _liqDiff.sub(curve.lambda.mul(_feeDiff)); _curveMultiplier = _curveMultiplier.div(_oUtil); } if (_totalShells != 0) { curves_ = _totalShells.mul(_curveMultiplier); enforceLiquidityInvariant(_totalShells, curves_, _oGLiq, _nGLiq, _omega, _psi); } } function enforceSwapInvariant( int128 _oGLiq, int128 _omega, int128 _nGLiq, int128 _psi ) private pure { int128 _nextUtil = _nGLiq - _psi; int128 _prevUtil = _oGLiq - _omega; int128 _diff = _nextUtil - _prevUtil; require(0 < _diff || _diff >= MAX_DIFF, "Curve/swap-invariant-violation"); } function enforceLiquidityInvariant( int128 _totalShells, int128 _newShells, int128 _oGLiq, int128 _nGLiq, int128 _omega, int128 _psi ) internal pure { if (_totalShells == 0 || 0 == _totalShells + _newShells) return; int128 _prevUtilPerShell = _oGLiq.sub(_omega).div(_totalShells); int128 _nextUtilPerShell = _nGLiq.sub(_psi).div(_totalShells.add(_newShells)); int128 _diff = _nextUtilPerShell - _prevUtilPerShell; require(0 < _diff || _diff >= MAX_DIFF, "Curve/liquidity-invariant-violation"); } function enforceHalts( Storage.Curve storage curve, int128 _oGLiq, int128 _nGLiq, int128[] memory _oBals, int128[] memory _nBals, int128[] memory _weights ) private view { uint256 _length = _nBals.length; int128 _alpha = curve.alpha; for (uint256 i = 0; i < _length; i++) { int128 _nIdeal = _nGLiq.mul(_weights[i]); if (_nBals[i] > _nIdeal) { int128 _upperAlpha = ONE + _alpha; int128 _nHalt = _nIdeal.mul(_upperAlpha); if (_nBals[i] > _nHalt) { int128 _oHalt = _oGLiq.mul(_weights[i]).mul(_upperAlpha); if (_oBals[i] < _oHalt) revert("Curve/upper-halt"); if (_nBals[i] - _nHalt > _oBals[i] - _oHalt) revert("Curve/upper-halt"); } } else { int128 _lowerAlpha = ONE - _alpha; int128 _nHalt = _nIdeal.mul(_lowerAlpha); if (_nBals[i] < _nHalt) { int128 _oHalt = _oGLiq.mul(_weights[i]); _oHalt = _oHalt.mul(_lowerAlpha); if (_oBals[i] > _oHalt) revert("Curve/lower-halt"); if (_nHalt - _nBals[i] > _oHalt - _oBals[i]) revert("Curve/lower-halt"); } } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.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); } 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); } } } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IOracle { function acceptOwnership() external; function accessController() external view returns (address); function aggregator() external view returns (address); function confirmAggregator(address _aggregator) external; function decimals() external view returns (uint8); function description() external view returns (string memory); function getAnswer(uint256 _roundId) external view returns (int256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getTimestamp(uint256 _roundId) external view returns (uint256); function latestAnswer() external view returns (int256); function latestRound() external view returns (uint256); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestTimestamp() external view returns (uint256); function owner() external view returns (address); function phaseAggregators(uint16) external view returns (address); function phaseId() external view returns (uint16); function proposeAggregator(address _aggregator) external; function proposedAggregator() external view returns (address); function proposedGetRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function setController(address _accessController) external; function transferOwnership(address _to) external; function version() external view returns (uint256); } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IAssimilator.sol"; import "./lib/ABDKMath64x64.sol"; library Assimilators { using ABDKMath64x64 for int128; using Address for address; IAssimilator public constant iAsmltr = IAssimilator(address(0)); function delegate(address _callee, bytes memory _data) internal returns (bytes memory) { require(_callee.isContract(), "Assimilators/callee-is-not-a-contract"); // solhint-disable-next-line (bool _success, bytes memory returnData_) = _callee.delegatecall(_data); // solhint-disable-next-line assembly { if eq(_success, 0) { revert(add(returnData_, 0x20), returndatasize()) } } return returnData_; } function getRate(address _assim) internal view returns (uint256 amount_) { amount_ = IAssimilator(_assim).getRate(); } function viewRawAmount(address _assim, int128 _amt) internal view returns (uint256 amount_) { amount_ = IAssimilator(_assim).viewRawAmount(_amt); } function viewRawAmountLPRatio( address _assim, uint256 _baseWeight, uint256 _quoteWeight, int128 _amount ) internal view returns (uint256 amount_) { amount_ = IAssimilator(_assim).viewRawAmountLPRatio(_baseWeight, _quoteWeight, address(this), _amount); } function viewNumeraireAmount(address _assim, uint256 _amt) internal view returns (int128 amt_) { amt_ = IAssimilator(_assim).viewNumeraireAmount(_amt); } function viewNumeraireAmountAndBalance(address _assim, uint256 _amt) internal view returns (int128 amt_, int128 bal_) { (amt_, bal_) = IAssimilator(_assim).viewNumeraireAmountAndBalance(address(this), _amt); } function viewNumeraireBalance(address _assim) internal view returns (int128 bal_) { bal_ = IAssimilator(_assim).viewNumeraireBalance(address(this)); } function viewNumeraireBalanceLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _assim ) internal view returns (int128 bal_) { bal_ = IAssimilator(_assim).viewNumeraireBalanceLPRatio(_baseWeight, _quoteWeight, address(this)); } function intakeRaw(address _assim, uint256 _amt) internal returns (int128 amt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.intakeRaw.selector, _amt); amt_ = abi.decode(delegate(_assim, data), (int128)); } function intakeRawAndGetBalance(address _assim, uint256 _amt) internal returns (int128 amt_, int128 bal_) { bytes memory data = abi.encodeWithSelector(iAsmltr.intakeRawAndGetBalance.selector, _amt); (amt_, bal_) = abi.decode(delegate(_assim, data), (int128, int128)); } function intakeNumeraire(address _assim, int128 _amt) internal returns (uint256 amt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.intakeNumeraire.selector, _amt); amt_ = abi.decode(delegate(_assim, data), (uint256)); } function intakeNumeraireLPRatio( address _assim, uint256 _baseWeight, uint256 _quoteWeight, int128 _amount ) internal returns (uint256 amt_) { bytes memory data = abi.encodeWithSelector( iAsmltr.intakeNumeraireLPRatio.selector, _baseWeight, _quoteWeight, address(this), _amount ); amt_ = abi.decode(delegate(_assim, data), (uint256)); } function outputRaw( address _assim, address _dst, uint256 _amt ) internal returns (int128 amt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.outputRaw.selector, _dst, _amt); amt_ = abi.decode(delegate(_assim, data), (int128)); amt_ = amt_.neg(); } function outputRawAndGetBalance( address _assim, address _dst, uint256 _amt ) internal returns (int128 amt_, int128 bal_) { bytes memory data = abi.encodeWithSelector(iAsmltr.outputRawAndGetBalance.selector, _dst, _amt); (amt_, bal_) = abi.decode(delegate(_assim, data), (int128, int128)); amt_ = amt_.neg(); } function outputNumeraire( address _assim, address _dst, int128 _amt ) internal returns (uint256 amt_) { bytes memory data = abi.encodeWithSelector(iAsmltr.outputNumeraire.selector, _dst, _amt.abs()); amt_ = abi.decode(delegate(_assim, data), (uint256)); } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IAssimilator { function getRate() external view returns (uint256); function intakeRaw(uint256 amount) external returns (int128); function intakeRawAndGetBalance(uint256 amount) external returns (int128, int128); function intakeNumeraire(int128 amount) external returns (uint256); function intakeNumeraireLPRatio( uint256, uint256, address, int128 ) external returns (uint256); function outputRaw(address dst, uint256 amount) external returns (int128); function outputRawAndGetBalance(address dst, uint256 amount) external returns (int128, int128); function outputNumeraire(address dst, int128 amount) external returns (uint256); function viewRawAmount(int128) external view returns (uint256); function viewRawAmountLPRatio( uint256, uint256, address, int128 ) external view returns (uint256); function viewNumeraireAmount(uint256) external view returns (int128); function viewNumeraireBalanceLPRatio( uint256, uint256, address ) external view returns (int128); function viewNumeraireBalance(address) external view returns (int128); function viewNumeraireAmountAndBalance(address, uint256) external view returns (int128, int128); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; library UnsafeMath64x64 { /** * Calculate x * y rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; return int128 (result); } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_div (int128 x, int128 y) internal pure returns (int128) { int256 result = (int256 (x) << 64) / y; return int128 (result); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ 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) { 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)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } }
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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, sender, recipient, amount); _approve( curve, sender, msg.sender, sub(curve.allowances[sender][msg.sender], amount, "Curve/insufficient-allowance") ); return true; }
1,539,401
/** *Submitted for verification at Etherscan.io on 2020-09-28 */ // 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; } } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // /** * @notice Interface for Curve.fi's REN pool. * Note that we are using array of 2 as Curve's REN pool contains only WBTC and renBTC. */ interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // renBTC pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } // /** * @notice Interface for Curve.fi's liquidity guage. */ interface ICurveGauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; } // /** * @notice Interface for Curve.fi's CRV minter. */ interface ICurveMinter { function mint(address) external; } // /** * @notice Interface for Uniswap's router. */ interface IUniswapRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } // /** * @notice Interface for Strategies. */ interface IStrategy { /** * @dev Returns the token address that the strategy expects. */ function want() external view returns (address); /** * @dev Returns the total amount of tokens deposited in this strategy. */ function balanceOf() external view returns (uint256); /** * @dev Deposits the token to start earning. */ function deposit() external; /** * @dev Withdraws partial funds from the strategy. */ function withdraw(uint256 _amount) external; /** * @dev Withdraws all funds from the strategy. */ function withdrawAll() external returns (uint256); /** * @dev Claims yield and convert it back to want token. */ function harvest() external; } // /** * @dev Earning strategy that accepts renCRV, earns CRV and converts CRV back to renCRV as yield. */ contract StrategyCurveRenBTC is IStrategy { using SafeERC20 for IERC20; using SafeMath for uint256; event Harvested(address indexed token, uint256 amount); address internal constant override want = address(0x49849C98ae39Fff122806C06791Fa73784FB3675); // renCrv token address internal constant pool = address(0xB1F2cdeC61db658F091671F5f199635aEF202CAC); // renCrv guage address internal constant mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // Token minter address internal constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV token address internal constant uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2Router02 address internal constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH token. Used for crv <> weth <> wbtc route address internal constant wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // WBTC token address internal constant curve = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); // REN swap address internal vault; constructor(address _vault) public { require(_vault != address(0x0), "vault not set"); vault = _vault; } /** * @dev Deposits all renCRV into Curve liquidity gauge to earn CRV. */ function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_want > 0) { IERC20(want).safeApprove(pool, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(want).safeApprove(pool, _want); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ICurveGauge(pool).deposit(_want); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } /** * @dev Withdraw partial funds, normally used with a vault withdrawal */ function withdraw(uint256 _amount) public override { require(msg.sender == vault, "not vault"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 _balance = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(want).safeTransfer(vault, _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Withdraw all funds, normally used when migrating strategies */ function withdrawAll() public override returns (uint256 balance) { require(msg.sender == vault, "not vault"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ICurveGauge(pool).withdraw(ICurveGauge(pool).balanceOf(address(this))); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balance = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(want).safeTransfer(vault, balance); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Claims CRV from Curve and convert it back to renCRV. * Anyone can trigger the harvest! */ function harvest() public override { // Claims CRV from Curve ICurveMinter(mintr).mint(pool); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 _crv = IERC20(crv).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // Uniswap: CRV --> WETH --> WBTC if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(crv).safeApprove(uni, _crv); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC address[] memory path = new address[](3); path[0] = crv; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC path[1] = weth; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC path[2] = wbtc; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IUniswapRouter(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } // Curve: WBTC --> renCRV uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_wbtc > 0) { IERC20(wbtc).safeApprove(curve, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(wbtc).safeApprove(curve, _wbtc); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ICurveFi(curve).add_liquidity([0, _wbtc], 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } uint256 _want = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_want > 0) { deposit(); } emit Harvested(want, _want); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Withdraw some tokens from the gauge. */ function _withdrawSome(uint256 _amount) internal returns (uint256) { ICurveGauge(pool).withdraw(_amount); return _amount; } /** * @dev Returns the amount of tokens deposited in the strategy. */ function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Returns the amount of tokens deposited in the gauge. */ function balanceOfPool() public view returns (uint256) { return ICurveGauge(pool).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Returns the amount of tokens deposited in strategy + gauge. */ function balanceOf() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } }
Withdraw partial funds, normally used with a vault withdrawal/
function withdraw(uint256 _amount) public override { if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } }
12,905,145
pragma solidity ^0.4.10; import './ValueTokenAgent.sol'; import './ValueToken.sol'; import './IDividendWallet.sol'; import '../common/SafeMath.sol'; import '../common/ReentryProtected.sol'; /* Based on https://medium.com/@weka/dividend-bearing-tokens-on-ethereum-42d01c710657 */ /**@dev Can distribute all stored ether among token holders */ contract DividendWallet is ValueTokenAgent, IDividendWallet, SafeMath, ReentryProtected { event Withdraw(address receiver, uint256 amount); /**@dev Ether balance to withdraw */ mapping (address => uint256) public etherBalance; /**@dev The contract balance at last claim (transfer or withdraw) */ uint lastBalance; /**@dev Sets token to watch transfer operations */ function DividendWallet(ValueToken token) ValueTokenAgent(token) { } function () payable {} /**@dev ValueTokenAgnet override. Validates the state of each holder's dividend to be paid */ function tokenIsBeingTransferred(address from, address to, uint256 amount) valueTokenOnly { require(from != to); updateHolder(from); updateHolder(to); } /**@dev ValueTokenAgent override */ function tokenChanged(address holder, uint256 amount) valueTokenOnly { updateHolder(holder); } /**@dev Withdraws all sender's ether balance */ function withdrawAll() returns (bool) { require(!valueToken.reserved(msg.sender)); return doWithdraw(msg.sender, etherBalanceOf(msg.sender)); } /**@dev Account specific ethereum balance getter */ function etherBalanceOf(address holder) constant returns (uint balance) { balance = safeAdd(etherBalance[holder], claimableEther(holder)); } /** @dev Updates holder state before transfer tokens or ether withdrawal */ function updateHolder(address holder) internal; /**@dev Returns amount of ether that specified holder can withdraw */ function claimableEther(address holder) internal constant returns (uint256 eth) {holder; eth;} /**@dev Account withdrawl function */ //function doWithdraw(address holder, uint amount) internal returns (bool); function doWithdraw(address holder, uint amount) internal // preventReentry returns (bool success) { updateHolder(holder); // check balance and withdraw on valid amount require(amount <= etherBalance[holder]); etherBalance[holder] = safeSub(etherBalance[holder], amount); lastBalance = safeSub(lastBalance, amount); Withdraw(holder, amount); holder.transfer(amount); success = true; } }
Account specific ethereum balance getter /
function etherBalanceOf(address holder) constant returns (uint balance) { balance = safeAdd(etherBalance[holder], claimableEther(holder)); }
13,028,689
./partial_match/3/0xE452Db0Ce76054692fd6dDfa29aaF329B55341c0/sources/TEDswapPool1.sol
Subtract `reserves`.
function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); require(_publicSwap, "ERR_SWAP_NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO exceeded"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); uint reserves = calcReservesFromFee(tokenInFee, _reservesRatio); inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); emit LOG_ADD_RESERVES(address(tokenIn), reserves); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); }
5,085,601
pragma solidity 0.5.16; import {DogeClaimManager} from "./DogeClaimManager.sol"; import {DogeErrorCodes} from "./DogeErrorCodes.sol"; import {DogeSuperblocks} from "./DogeSuperblocks.sol"; import {DogeMessageLibrary} from "./DogeParser/DogeMessageLibrary.sol"; import {IScryptChecker} from "./IScryptChecker.sol"; import {IScryptCheckerListener} from "./IScryptCheckerListener.sol"; // @dev - Manages a battle session between superblock submitter and challenger contract DogeBattleManager is DogeErrorCodes, IScryptCheckerListener { enum ChallengeState { Unchallenged, // Unchallenged submission Challenged, // Claims was challenged QueryMerkleRootHashes, // Challenger expecting block hashes RespondMerkleRootHashes, // Blcok hashes were received and verified QueryBlockHeader, // Challenger is requesting block headers RespondBlockHeader, // All block headers were received VerifyScryptHash, RequestScryptVerification, PendingScryptVerification, PendingVerification, // Pending superblock verification SuperblockVerified, // Superblock verified SuperblockFailed // Superblock not valid } enum BlockInfoStatus { Nonexistent, Uninitialized, Requested, ScryptHashPending, ScryptHashVerified, ScryptHashFailed } struct BlockInfo { bytes32 prevBlock; uint64 timestamp; uint32 bits; BlockInfoStatus status; bytes powBlockHeader; bytes32 scryptHash; } struct BattleSession { bytes32 id; bytes32 superblockHash; address submitter; address challenger; uint lastActionTimestamp; // Last action timestamp uint lastActionClaimant; // Number last action submitter uint lastActionChallenger; // Number last action challenger uint actionsCounter; // Counter session actions bytes32[] blockHashes; // Block hashes uint countBlockHeaderQueries; // Number of block header queries uint countBlockHeaderResponses; // Number of block header responses mapping (bytes32 => BlockInfo) blocksInfo; bytes32 pendingScryptHashId; ChallengeState challengeState; // Claim state } struct ScryptHashVerification { bytes32 sessionId; bytes32 blockSha256Hash; } mapping (bytes32 => BattleSession) public sessions; uint public sessionsCount = 0; uint public superblockDuration; // Superblock duration (in seconds) uint public superblockTimeout; // Timeout action (in seconds) // Pending Scrypt Hash verifications uint public numScryptHashVerifications; mapping (bytes32 => ScryptHashVerification) public scryptHashVerifications; // network that the stored blocks belong to DogeMessageLibrary.Network private net; // ScryptHash checker IScryptChecker public trustedScryptChecker; // Doge claim manager DogeClaimManager trustedDogeClaimManager; // Superblocks contract DogeSuperblocks trustedSuperblocks; event NewBattle(bytes32 superblockHash, bytes32 sessionId, address submitter, address challenger); event ChallengerConvicted(bytes32 superblockHash, bytes32 sessionId, address challenger); event SubmitterConvicted(bytes32 superblockHash, bytes32 sessionId, address submitter); event QueryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address submitter); event RespondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32[] blockHashes); event QueryBlockHeader(bytes32 superblockHash, bytes32 sessionId, address submitter, bytes32 blockSha256Hash); event RespondBlockHeader(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32 blockScryptHash, bytes blockHeader, bytes powBlockHeader); event RequestScryptHashValidation(bytes32 superblockHash, bytes32 sessionId, bytes32 blockScryptHash, bytes blockHeader, bytes32 proposalId, address submitter); event ResolvedScryptHashValidation(bytes32 superblockHash, bytes32 sessionId, bytes32 blockScryptHash, bytes32 blockSha256Hash, bytes32 proposalId, address challenger, bool valid); event ErrorBattle(bytes32 sessionId, uint err); modifier onlyFrom(address sender) { require(msg.sender == sender); _; } modifier onlyClaimant(bytes32 sessionId) { require(msg.sender == sessions[sessionId].submitter); _; } modifier onlyChallenger(bytes32 sessionId) { require(msg.sender == sessions[sessionId].challenger); _; } // @dev – Configures the contract managing superblocks battles // @param _network Network type to use for block difficulty validation // @param _superblocks Contract that manages superblocks // @param _superblockDuration Superblock duration (in seconds) // @param _superblockTimeout Time to wait for challenges (in seconds) constructor( DogeMessageLibrary.Network _network, DogeSuperblocks _superblocks, uint _superblockDuration, uint _superblockTimeout ) public { net = _network; trustedSuperblocks = _superblocks; superblockDuration = _superblockDuration; superblockTimeout = _superblockTimeout; } // @dev - sets ScryptChecker instance associated with this DogeClaimManager contract. // Once trustedScryptChecker has been set, it cannot be changed. // An address of 0x0 means trustedScryptChecker hasn't been set yet. // // @param _scryptChecker - address of the ScryptChecker contract to be associated with DogeClaimManager function setScryptChecker(IScryptChecker _scryptChecker) public { require(address(trustedScryptChecker) == address(0x0) && address(_scryptChecker) != address(0x0)); trustedScryptChecker = _scryptChecker; } function setDogeClaimManager(DogeClaimManager _dogeClaimManager) public { require(address(trustedDogeClaimManager) == address(0x0) && address(_dogeClaimManager) != address(0x0)); trustedDogeClaimManager = _dogeClaimManager; } // @dev - Start a battle session function beginBattleSession(bytes32 superblockHash, address submitter, address challenger) public onlyFrom(address(trustedDogeClaimManager)) returns (bytes32) { bytes32 sessionId = keccak256(abi.encode(superblockHash, msg.sender, sessionsCount)); BattleSession storage session = sessions[sessionId]; session.id = sessionId; session.superblockHash = superblockHash; session.submitter = submitter; session.challenger = challenger; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = 0; session.lastActionClaimant = 1; // Force challenger to start session.actionsCounter = 1; session.challengeState = ChallengeState.Challenged; sessionsCount += 1; emit NewBattle(superblockHash, sessionId, submitter, challenger); return sessionId; } // @dev - Challenger makes a query for superblock hashes function doQueryMerkleRootHashes(BattleSession storage session) internal returns (uint) { if (!hasDeposit(msg.sender, respondMerkleRootHashesCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.Challenged) { session.challengeState = ChallengeState.QueryMerkleRootHashes; assert(msg.sender == session.challenger); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondMerkleRootHashesCost); if (err != ERR_SUPERBLOCK_OK) { return err; } return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - Challenger makes a query for superblock hashes function queryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doQueryMerkleRootHashes(session); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryMerkleRootHashes(superblockHash, sessionId, session.submitter); } } // @dev - Submitter sends hashes to verify superblock merkle root function doVerifyMerkleRootHashes(BattleSession storage session, bytes32[] memory blockHashes) internal returns (uint) { if (!hasDeposit(msg.sender, verifySuperblockCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } require(session.blockHashes.length == 0); if (session.challengeState == ChallengeState.QueryMerkleRootHashes) { (bytes32 merkleRoot, , , , bytes32 lastHash, , , , ) = getSuperblockInfo(session.superblockHash); if (lastHash != blockHashes[blockHashes.length - 1]) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } if (merkleRoot != DogeMessageLibrary.makeMerkle(blockHashes)) { return ERR_SUPERBLOCK_INVALID_MERKLE; } (uint err, ) = bondDeposit(session.superblockHash, msg.sender, verifySuperblockCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.blockHashes = blockHashes; session.challengeState = ChallengeState.RespondMerkleRootHashes; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the submitter to respond to challenger queries function respondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, bytes32[] memory blockHashes) public onlyClaimant(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doVerifyMerkleRootHashes(session, blockHashes); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; // Map blocks to prevent a malicious challenger from requesting one that doesn't exist for (uint i = 0; i < blockHashes.length; ++i) { session.blocksInfo[blockHashes[i]].status = BlockInfoStatus.Uninitialized; } emit RespondMerkleRootHashes(superblockHash, sessionId, session.challenger, blockHashes); } } // @dev - Challenger makes a query for block header data for a hash function doQueryBlockHeader(BattleSession storage session, bytes32 blockHash) internal returns (uint) { if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.VerifyScryptHash) { skipScryptHashVerification(session); } // TODO: see if this condition is worth refactoring if ((session.countBlockHeaderQueries == 0 && session.challengeState == ChallengeState.RespondMerkleRootHashes) || (session.countBlockHeaderQueries > 0 && session.challengeState == ChallengeState.RespondBlockHeader)) { require(session.countBlockHeaderQueries < session.blockHashes.length); require(session.blocksInfo[blockHash].status == BlockInfoStatus.Uninitialized); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.countBlockHeaderQueries += 1; session.blocksInfo[blockHash].status = BlockInfoStatus.Requested; session.challengeState = ChallengeState.QueryBlockHeader; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the challenger to start a query function queryBlockHeader(bytes32 superblockHash, bytes32 sessionId, bytes32 blockHash) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doQueryBlockHeader(session, blockHash); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryBlockHeader(superblockHash, sessionId, session.submitter, blockHash); } } // @dev - Verify that block timestamp is in the superblock timestamp interval function verifyTimestamp(bytes32 superblockHash, bytes memory blockHeader) internal view returns (bool) { uint blockTimestamp = DogeMessageLibrary.getTimestamp(blockHeader, 0); uint superblockTimestamp; (, , superblockTimestamp, , , , , , ) = getSuperblockInfo(superblockHash); // Block timestamp to be within the expected timestamp of the superblock return (blockTimestamp / superblockDuration <= superblockTimestamp / superblockDuration) && (blockTimestamp / superblockDuration >= superblockTimestamp / superblockDuration - 1); } // @dev - Generate request to verify block header scrypt hash function doVerifyScryptHash( bytes32 sessionId, bytes32 blockScryptHash, bytes32 blockSha256Hash, address submitter ) internal returns (bytes32) { numScryptHashVerifications += 1; bytes32 proposalId = keccak256(abi.encodePacked( blockScryptHash, submitter, numScryptHashVerifications )); scryptHashVerifications[proposalId] = ScryptHashVerification({ sessionId: sessionId, blockSha256Hash: blockSha256Hash }); return proposalId; } // @dev - Verify Dogecoin block AuxPoW function verifyBlockAuxPoW( BlockInfo storage blockInfo, bytes32 proposedBlockScryptHash, bytes memory blockHeader ) internal returns (uint, bytes memory) { (uint err, , bytes32 blockScryptHash, bool isMergeMined) = DogeMessageLibrary.verifyBlockHeader(blockHeader, 0, blockHeader.length, proposedBlockScryptHash); if (err != 0) { return (err, new bytes(0)); } bytes memory powBlockHeader = (isMergeMined) ? DogeMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) : DogeMessageLibrary.sliceArray(blockHeader, 0, 80); blockInfo.timestamp = DogeMessageLibrary.getTimestamp(blockHeader, 0); blockInfo.bits = DogeMessageLibrary.getBits(blockHeader, 0); blockInfo.prevBlock = DogeMessageLibrary.getHashPrevBlock(blockHeader, 0); blockInfo.scryptHash = blockScryptHash; blockInfo.powBlockHeader = powBlockHeader; return (ERR_SUPERBLOCK_OK, powBlockHeader); } // @dev - Verify block header sent by challenger function doVerifyBlockHeader( BattleSession storage session, bytes32 sessionId, bytes32 proposedBlockScryptHash, bytes memory blockHeader ) internal returns (uint, bytes memory) { // TODO: see if this should fund Scrypt verification if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return (ERR_SUPERBLOCK_MIN_DEPOSIT, new bytes(0)); } if (session.challengeState == ChallengeState.QueryBlockHeader) { bytes32 blockSha256Hash = bytes32(DogeMessageLibrary.dblShaFlipMem(blockHeader, 0, 80)); BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (blockInfo.status != BlockInfoStatus.Requested) { return (ERR_SUPERBLOCK_BAD_DOGE_STATUS, new bytes(0)); } if (!verifyTimestamp(session.superblockHash, blockHeader)) { return (ERR_SUPERBLOCK_BAD_TIMESTAMP, new bytes(0)); } (uint err, bytes memory powBlockHeader) = verifyBlockAuxPoW(blockInfo, proposedBlockScryptHash, blockHeader); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } blockInfo.status = BlockInfoStatus.ScryptHashPending; (err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } bytes32 pendingScryptHashId = doVerifyScryptHash( sessionId, blockInfo.scryptHash, blockSha256Hash, session.submitter ); session.countBlockHeaderResponses += 1; session.challengeState = ChallengeState.VerifyScryptHash; session.pendingScryptHashId = pendingScryptHashId; return (ERR_SUPERBLOCK_OK, powBlockHeader); } return (ERR_SUPERBLOCK_BAD_STATUS, new bytes(0)); } // @dev - For the submitter to respond to challenger queries function respondBlockHeader( bytes32 superblockHash, bytes32 sessionId, bytes32 blockScryptHash, bytes memory blockHeader ) public onlyClaimant(sessionId) { BattleSession storage session = sessions[sessionId]; (uint err, bytes memory powBlockHeader) = doVerifyBlockHeader(session, sessionId, blockScryptHash, blockHeader); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; emit RespondBlockHeader(superblockHash, sessionId, session.challenger, blockScryptHash, blockHeader, powBlockHeader); } } // @dev - Notify submitter to start scrypt hash verification function doRequestScryptHashValidation( BattleSession storage session, bytes32 superblockHash, bytes32 sessionId, bytes32 blockSha256Hash ) internal returns (uint) { if (!hasDeposit(msg.sender, queryMerkleRootHashesCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.VerifyScryptHash) { BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (blockInfo.status == BlockInfoStatus.ScryptHashPending) { (uint err, ) = bondDeposit(session.superblockHash, msg.sender, queryMerkleRootHashesCost); if (err != ERR_SUPERBLOCK_OK) { return err; } emit RequestScryptHashValidation(superblockHash, sessionId, blockInfo.scryptHash, blockInfo.powBlockHeader, session.pendingScryptHashId, session.submitter); session.challengeState = ChallengeState.RequestScryptVerification; return ERR_SUPERBLOCK_OK; } } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - Challenger requests to start scrypt hash verification function requestScryptHashValidation( bytes32 superblockHash, bytes32 sessionId, bytes32 blockSha256Hash ) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doRequestScryptHashValidation(session, superblockHash, sessionId, blockSha256Hash); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; } } // @dev - Validate superblock information from last blocks function validateLastBlocks(BattleSession storage session) internal view returns (uint) { if (session.blockHashes.length <= 0) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } uint lastTimestamp; uint prevTimestamp; uint32 lastBits; bytes32 parentId; (, , lastTimestamp, prevTimestamp, , lastBits, parentId, , ) = getSuperblockInfo(session.superblockHash); bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1]; if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } if (session.blocksInfo[blockSha256Hash].bits != lastBits) { return ERR_SUPERBLOCK_BAD_BITS; } if (session.blockHashes.length > 1) { blockSha256Hash = session.blockHashes[session.blockHashes.length - 2]; if (session.blocksInfo[blockSha256Hash].timestamp != prevTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } } else { (, , lastTimestamp, , , , , , ) = getSuperblockInfo(parentId); if (lastTimestamp != prevTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } } return ERR_SUPERBLOCK_OK; } // @dev - Validate superblock accumulated work function validateProofOfWork(BattleSession storage session) internal view returns (uint) { uint accWork; uint parentWork; bytes32 parentId; bytes32 prevBlock; uint parentTimestamp; uint gpTimestamp; uint32 prevBits; (, accWork, , , , , parentId, , ) = getSuperblockInfo(session.superblockHash); (, parentWork, parentTimestamp, gpTimestamp, prevBlock, prevBits, , , ) = getSuperblockInfo(parentId); uint idx = 0; uint work; while (idx < session.blockHashes.length) { bytes32 blockSha256Hash = session.blockHashes[idx]; uint32 bits = session.blocksInfo[blockSha256Hash].bits; if (session.blocksInfo[blockSha256Hash].prevBlock != prevBlock) { return ERR_SUPERBLOCK_BAD_PARENT; } if (net != DogeMessageLibrary.Network.REGTEST) { uint32 newBits = DogeMessageLibrary.calculateDigishieldDifficulty( int64(parentTimestamp) - int64(gpTimestamp), prevBits); if (net == DogeMessageLibrary.Network.TESTNET && session.blocksInfo[blockSha256Hash].timestamp - parentTimestamp > 120) { newBits = 0x1e0fffff; } if (bits != newBits) { return ERR_SUPERBLOCK_BAD_BITS; } } work += DogeMessageLibrary.diffFromBits(session.blocksInfo[blockSha256Hash].bits); prevBlock = blockSha256Hash; prevBits = session.blocksInfo[blockSha256Hash].bits; gpTimestamp = parentTimestamp; parentTimestamp = session.blocksInfo[blockSha256Hash].timestamp; idx += 1; } if (net != DogeMessageLibrary.Network.REGTEST && parentWork + work != accWork) { return ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK; } return ERR_SUPERBLOCK_OK; } // @dev - Verify whether a superblock's data is consistent // Only should be called when all block headers were submitted function doVerifySuperblock(BattleSession storage session, bytes32 sessionId) internal returns (uint) { if (session.challengeState == ChallengeState.VerifyScryptHash) { skipScryptHashVerification(session); } if (session.challengeState == ChallengeState.PendingVerification) { uint err; err = validateLastBlocks(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } err = validateProofOfWork(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } return 1; } else if (session.challengeState == ChallengeState.SuperblockFailed) { return 2; } return 0; } // @dev - Perform final verification once all blocks were submitted function verifySuperblock(bytes32 sessionId) public { BattleSession storage session = sessions[sessionId]; uint status = doVerifySuperblock(session, sessionId); if (status == 1) { convictChallenger(sessionId, session.challenger, session.superblockHash); } else if (status == 2) { convictSubmitter(sessionId, session.submitter, session.superblockHash); } } // @dev - Trigger conviction if response is not received in time function timeout(bytes32 sessionId) public returns (uint) { BattleSession storage session = sessions[sessionId]; if (session.challengeState == ChallengeState.PendingScryptVerification) { emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT); return ERR_SUPERBLOCK_NO_TIMEOUT; } if (session.challengeState == ChallengeState.SuperblockFailed || (session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout)) { convictSubmitter(sessionId, session.submitter, session.superblockHash); return ERR_SUPERBLOCK_OK; } else if (session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout) { convictChallenger(sessionId, session.challenger, session.superblockHash); return ERR_SUPERBLOCK_OK; } emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT); return ERR_SUPERBLOCK_NO_TIMEOUT; } // @dev - To be called when a challenger is convicted function convictChallenger(bytes32 sessionId, address challenger, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.submitter, session.challenger); disable(sessionId); emit ChallengerConvicted(superblockHash, sessionId, challenger); } // @dev - To be called when a submitter is convicted function convictSubmitter(bytes32 sessionId, address submitter, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.challenger, session.submitter); disable(sessionId); emit SubmitterConvicted(superblockHash, sessionId, submitter); } // @dev - Disable session // It should be called only when either the submitter or the challenger were convicted. function disable(bytes32 sessionId) internal { delete sessions[sessionId]; } // @dev Update scrypt verification result function notifyScryptHashResult( BattleSession storage session, bytes32 blockSha256Hash, bool valid ) internal { BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (valid){ blockInfo.status = BlockInfoStatus.ScryptHashVerified; if (session.countBlockHeaderResponses == session.blockHashes.length) { session.challengeState = ChallengeState.PendingVerification; } else { session.challengeState = ChallengeState.RespondBlockHeader; } } else { blockInfo.status = BlockInfoStatus.ScryptHashFailed; session.challengeState = ChallengeState.SuperblockFailed; } } // @dev - Skip scrypt hash verification function skipScryptHashVerification(BattleSession storage session) internal { require(session.pendingScryptHashId != 0x0); bytes32 pendingScryptHashId = session.pendingScryptHashId; ScryptHashVerification storage verification = scryptHashVerifications[pendingScryptHashId]; require(verification.sessionId != 0x0); notifyScryptHashResult(session, verification.blockSha256Hash, true); delete scryptHashVerifications[pendingScryptHashId]; session.pendingScryptHashId = 0x0; } // @dev - Compare two 80-byte Doge block headers function compareBlockHeader(bytes memory left, bytes memory right) internal pure returns (int) { require(left.length == 80); require(right.length == 80); int a; int b; // Compare first 32 bytes assembly { a := mload(add(left, 0x20)) b := mload(add(right, 0x20)) } if (a != b) { return a - b; } // Compare next 32 bytes assembly { a := mload(add(left, 0x40)) b := mload(add(right, 0x40)) } if (a != b) { return a - b; } // Compare last 32 bytes assembly { a := mload(add(left, 0x50)) b := mload(add(right, 0x50)) } // Note: There's a 16 bytes overlap with previous 32 bytes chunk // But comparing full 32 bytes is faster/cheaper return a - b; } // @dev - To be called after scrypt verification is submitted function scryptSubmitted( bytes32 scryptChallengeId, bytes32 _scryptHash, bytes calldata _data, address _submitter ) external onlyFrom(address(trustedScryptChecker)) { require(_data.length == 80); ScryptHashVerification storage verification = scryptHashVerifications[scryptChallengeId]; BattleSession storage session = sessions[verification.sessionId]; require(session.pendingScryptHashId == scryptChallengeId); require(session.challengeState == ChallengeState.RequestScryptVerification); require(session.submitter == _submitter); BlockInfo storage blockInfo = session.blocksInfo[verification.blockSha256Hash]; require(blockInfo.status == BlockInfoStatus.ScryptHashPending); require(blockInfo.scryptHash == _scryptHash); require(compareBlockHeader(blockInfo.powBlockHeader, _data) == 0); session.challengeState = ChallengeState.PendingScryptVerification; session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; } // @dev - Update session state with scrypt hash verification result function doNotifyScryptVerificationResult(bytes32 scryptChallengeId, bool succeeded) internal { ScryptHashVerification storage verification = scryptHashVerifications[scryptChallengeId]; BattleSession storage session = sessions[verification.sessionId]; require(session.pendingScryptHashId == scryptChallengeId); require(session.challengeState == ChallengeState.PendingScryptVerification); BlockInfo storage blockInfo = session.blocksInfo[verification.blockSha256Hash]; require(blockInfo.status == BlockInfoStatus.ScryptHashPending); notifyScryptHashResult(session, verification.blockSha256Hash, succeeded); // Restart challenger timeout session.lastActionTimestamp = block.timestamp; emit ResolvedScryptHashValidation( session.superblockHash, verification.sessionId, blockInfo.scryptHash, verification.blockSha256Hash, scryptChallengeId, session.challenger, succeeded ); } // @dev - Scrypt verification succeeded function scryptVerified(bytes32 scryptChallengeId) external onlyFrom(address(trustedScryptChecker)) { doNotifyScryptVerificationResult(scryptChallengeId, true); } // @dev - Scrypt verification failed function scryptFailed(bytes32 scryptChallengeId) external onlyFrom(address(trustedScryptChecker)) { doNotifyScryptVerificationResult(scryptChallengeId, false); } // @dev - Check if a session's challenger did not respond before timeout function getChallengerHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.challengeState != ChallengeState.PendingScryptVerification && session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Check if a session's submitter did not respond before timeout function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.challengeState != ChallengeState.PendingScryptVerification && session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Return Doge block hashes associated with a certain battle session function getDogeBlockHashes(bytes32 sessionId) public view returns (bytes32[] memory) { return sessions[sessionId].blockHashes; } // @dev - To be called when a battle sessions was decided function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) internal { trustedDogeClaimManager.sessionDecided(sessionId, superblockHash, winner, loser); } // @dev - Retrieve superblock information function getSuperblockInfo(bytes32 superblockHash) internal view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, DogeSuperblocks.Status _status ) { return trustedSuperblocks.getSuperblock(superblockHash); } // @dev - Verify whether a user has a certain amount of deposits or more function hasDeposit(address who, uint amount) internal view returns (bool) { return trustedDogeClaimManager.getDeposit(who) >= amount; } // @dev – locks up part of a user's deposit into a claim. function bondDeposit(bytes32 superblockHash, address account, uint amount) internal returns (uint, uint) { return trustedDogeClaimManager.bondDeposit(superblockHash, account, amount); } }
- Challenger requests to start scrypt hash verification
function requestScryptHashValidation( bytes32 superblockHash, bytes32 sessionId, bytes32 blockSha256Hash ) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doRequestScryptHashValidation(session, superblockHash, sessionId, blockSha256Hash); if (err != 0) { emit ErrorBattle(sessionId, err); session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; } }
6,366,493
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./IConverter.sol"; import "./IVaultManager.sol"; import "./IStableSwap3Pool.sol"; contract StableSwap3PoolConverter is IConverter { using SafeMath for uint; using SafeERC20 for IERC20; IERC20[3] public tokens; // DAI, USDC, USDT IERC20 public token3CRV; // 3Crv address public governance; IStableSwap3Pool public stableSwap3Pool; IVaultManager public vaultManager; constructor (IERC20 _tokenDAI, IERC20 _tokenUSDC, IERC20 _tokenUSDT, IERC20 _token3CRV, IStableSwap3Pool _stableSwap3Pool, IVaultManager _vaultManager) public { tokens[0] = _tokenDAI; tokens[1] = _tokenUSDC; tokens[2] = _tokenUSDT; token3CRV = _token3CRV; stableSwap3Pool = _stableSwap3Pool; tokens[0].safeApprove(address(stableSwap3Pool), uint(-1)); tokens[1].safeApprove(address(stableSwap3Pool), uint(-1)); tokens[2].safeApprove(address(stableSwap3Pool), uint(-1)); token3CRV.safeApprove(address(stableSwap3Pool), uint(-1)); vaultManager = _vaultManager; governance = msg.sender; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setStableSwap3Pool(IStableSwap3Pool _stableSwap3Pool) public { require(msg.sender == governance, "!governance"); stableSwap3Pool = _stableSwap3Pool; tokens[0].safeApprove(address(stableSwap3Pool), uint(-1)); tokens[1].safeApprove(address(stableSwap3Pool), uint(-1)); tokens[2].safeApprove(address(stableSwap3Pool), uint(-1)); token3CRV.safeApprove(address(stableSwap3Pool), uint(-1)); } function setVaultManager(IVaultManager _vaultManager) public { require(msg.sender == governance, "!governance"); vaultManager = _vaultManager; } function approveForSpender(IERC20 _token, address _spender, uint _amount) external { require(msg.sender == governance, "!governance"); _token.safeApprove(_spender, _amount); } function token() external override returns (address _share) { _share = address(token3CRV); } function convert(address _input, address _output, uint _inputAmount) external override returns (uint _outputAmount) { require(msg.sender == governance || vaultManager.vaults(msg.sender), "!(governance||vault)"); if (_output == address(token3CRV)) { // convert to 3CRV uint[3] memory amounts; for (uint8 i = 0; i < 3; i++) { if (_input == address(tokens[i])) { amounts[i] = _inputAmount; uint _before = token3CRV.balanceOf(address(this)); stableSwap3Pool.add_liquidity(amounts, 1); uint _after = token3CRV.balanceOf(address(this)); _outputAmount = _after.sub(_before); token3CRV.safeTransfer(msg.sender, _outputAmount); return _outputAmount; } } } else if (_input == address(token3CRV)) { // convert from 3CRV for (uint8 i = 0; i < 3; i++) { if (_output == address(tokens[i])) { uint _before = tokens[i].balanceOf(address(this)); stableSwap3Pool.remove_liquidity_one_coin(_inputAmount, i, 1); uint _after = tokens[i].balanceOf(address(this)); _outputAmount = _after.sub(_before); tokens[i].safeTransfer(msg.sender, _outputAmount); return _outputAmount; } } } return 0; } function convert_rate(address _input, address _output, uint _inputAmount) external override view returns (uint _outputAmount) { if (_output == address(token3CRV)) { // convert to 3CRV uint[3] memory amounts; for (uint8 i = 0; i < 3; i++) { if (_input == address(tokens[i])) { amounts[i] = _inputAmount; return stableSwap3Pool.calc_token_amount(amounts, true); } } } else if (_input == address(token3CRV)) { // convert from 3CRV for (uint8 i = 0; i < 3; i++) { if (_output == address(tokens[i])) { // @dev this is for UI reference only, the actual share price (stable/CRV) will be re-calculated on-chain when we do convert() return stableSwap3Pool.calc_withdraw_one_coin(_inputAmount, i); } } } return 0; } // 0: DAI, 1: USDC, 2: USDT function convert_stables(uint[3] calldata amounts) external override returns (uint _shareAmount) { require(msg.sender == governance || vaultManager.vaults(msg.sender), "!(governance||vault)"); uint _before = token3CRV.balanceOf(address(this)); stableSwap3Pool.add_liquidity(amounts, 1); uint _after = token3CRV.balanceOf(address(this)); _shareAmount = _after.sub(_before); token3CRV.safeTransfer(msg.sender, _shareAmount); } function get_dy(int128 i, int128 j, uint dx) external override view returns (uint) { return stableSwap3Pool.get_dy(i, j, dx); } function exchange(int128 i, int128 j, uint dx, uint min_dy) external override returns (uint dy) { require(msg.sender == governance || vaultManager.vaults(msg.sender), "!(governance||vault)"); IERC20 _output = tokens[uint8(j)]; uint _before = _output.balanceOf(address(this)); stableSwap3Pool.exchange(i, j, dx, min_dy); uint _after = _output.balanceOf(address(this)); dy = _after.sub(_before); _output.safeTransfer(msg.sender, dy); } function calc_token_amount(uint[3] calldata amounts, bool deposit) external override view returns (uint _shareAmount) { _shareAmount = stableSwap3Pool.calc_token_amount(amounts, deposit); } function calc_token_amount_withdraw(uint _shares, address _output) external override view returns (uint) { for (uint8 i = 0; i < 3; i++) { if (_output == address(tokens[i])) { return stableSwap3Pool.calc_withdraw_one_coin(_shares, i); } } return 0; } function governanceRecoverUnsupported(IERC20 _token, uint _amount, address _to) external { require(msg.sender == governance, "!governance"); _token.transfer(_to, _amount); } }
0: DAI, 1: USDC, 2: USDT
function convert_stables(uint[3] calldata amounts) external override returns (uint _shareAmount) { require(msg.sender == governance || vaultManager.vaults(msg.sender), "!(governance||vault)"); uint _before = token3CRV.balanceOf(address(this)); stableSwap3Pool.add_liquidity(amounts, 1); uint _after = token3CRV.balanceOf(address(this)); _shareAmount = _after.sub(_before); token3CRV.safeTransfer(msg.sender, _shareAmount); }
6,385,436
pragma solidity ^0.4.18; interface ConflictResolutionInterface { function minHouseStake(uint activeGames) public pure returns(uint); function maxBalance() public pure returns(int); function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool); function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _playerSeed ) public view returns(int); function serverForceGameEnd( uint8 gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view returns(int); function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view returns(int); } contract ConflictResolution is ConflictResolutionInterface { uint public constant DICE_RANGE = 100; uint public constant HOUSE_EDGE = 150; uint public constant HOUSE_EDGE_DIVISOR = 10000; uint public constant SERVER_TIMEOUT = 6 hours; uint public constant PLAYER_TIMEOUT = 6 hours; uint8 public constant DICE_LOWER = 1; ///< @dev dice game lower number wins uint8 public constant DICE_HIGHER = 2; ///< @dev dice game higher number wins uint public constant MAX_BET_VALUE = 2e16; /// max 0.02 ether bet uint public constant MIN_BET_VALUE = 1e13; /// min 0.00001 ether bet int public constant NOT_ENDED_FINE = 1e15; /// 0.001 ether int public constant MAX_BALANCE = int(MAX_BET_VALUE) * 100 * 5; modifier onlyValidBet(uint8 _gameType, uint _betNum, uint _betValue) { require(isValidBet(_gameType, _betNum, _betValue)); _; } modifier onlyValidBalance(int _balance, uint _gameStake) { // safe to cast gameStake as range is fixed require(-int(_gameStake) <= _balance && _balance < MAX_BALANCE); _; } /** * @dev Check if bet is valid. * @param _gameType Game type. * @param _betNum Number of bet. * @param _betValue Value of bet. * @return True if bet is valid false otherwise. */ function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool) { bool validValue = MIN_BET_VALUE <= _betValue && _betValue <= MAX_BET_VALUE; bool validGame = false; if (_gameType == DICE_LOWER) { validGame = _betNum > 0 && _betNum < DICE_RANGE - 1; } else if (_gameType == DICE_HIGHER) { validGame = _betNum > 0 && _betNum < DICE_RANGE - 1; } else { validGame = false; } return validValue && validGame; } /** * @return Max balance. */ function maxBalance() public pure returns(int) { return MAX_BALANCE; } /** * Calculate minimum needed house stake. */ function minHouseStake(uint activeGames) public pure returns(uint) { return MathUtil.min(activeGames, 1) * MAX_BET_VALUE * 400; } /** * @dev Calculates game result and returns new balance. * @param _gameType Type of game. * @param _betNum Bet number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _serverSeed Server's seed of current round. * @param _playerSeed Player's seed of current round. * @return New game session balance. */ function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _playerSeed ) public view onlyValidBet(_gameType, _betNum, _betValue) onlyValidBalance(_balance, _stake) returns(int) { assert(_serverSeed != 0 && _playerSeed != 0); int newBalance = processBet(_gameType, _betNum, _betValue, _balance, _serverSeed, _playerSeed); // do not allow balance below player stake int stake = int(_stake); // safe to cast as stake range is fixed if (newBalance < -stake) { newBalance = -stake; } return newBalance; } /** * @dev Force end of game if player does not respond. Only possible after a time period. * to give the player a chance to respond. * @param _gameType Game type. * @param _betNum Bet number. * @param _betValue Bet value. * @param _balance Current balance. * @param _stake Player stake. * @param _endInitiatedTime Time server initiated end. * @return New game session balance. */ function serverForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view onlyValidBalance(_balance, _stake) returns(int) { require(_endInitiatedTime + SERVER_TIMEOUT <= block.timestamp); require(isValidBet(_gameType, _betNum, _betValue) || (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0)); // following casts and calculations are safe as ranges are fixed // assume player has lost int newBalance = _balance - int(_betValue); // penalize player as he didn't end game newBalance -= NOT_ENDED_FINE; // do not allow balance below player stake int stake = int(_stake); // safe to cast as stake range is fixed if (newBalance < -stake) { newBalance = -stake; } return newBalance; } /** * @dev Force end of game if server does not respond. Only possible after a time period * to give the server a chance to respond. * @param _gameType Game type. * @param _betNum Bet number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _endInitiatedTime Time server initiated end. * @return New game session balance. */ function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view onlyValidBalance(_balance, _stake) returns(int) { require(_endInitiatedTime + PLAYER_TIMEOUT <= block.timestamp); require(isValidBet(_gameType, _betNum, _betValue) || (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0)); int profit = 0; if (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0) { // player cancelled game without playing profit = 0; } else { profit = int(calculateProfit(_gameType, _betNum, _betValue)); // safe to cast as ranges are limited } // penalize server as it didn't end game profit += NOT_ENDED_FINE; return _balance + profit; } /** * @dev Calculate new balance after executing bet. * @param _gameType game type. * @param _betNum Bet Number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _serverSeed Server's seed * @param _playerSeed Player's seed * return new balance. */ function processBet( uint8 _gameType, uint _betNum, uint _betValue, int _balance, bytes32 _serverSeed, bytes32 _playerSeed ) private pure returns (int) { bool won = hasPlayerWon(_gameType, _betNum, _serverSeed, _playerSeed); if (!won) { return _balance - int(_betValue); // safe to cast as ranges are fixed } else { int profit = calculateProfit(_gameType, _betNum, _betValue); return _balance + profit; } } /** * @dev Calculate player profit. * @param _gameType type of game. * @param _betNum bet numbe. * @param _betValue bet value. * return profit of player */ function calculateProfit(uint8 _gameType, uint _betNum, uint _betValue) private pure returns(int) { uint betValueInGwei = _betValue / 1e9; // convert to gwei int res = 0; if (_gameType == DICE_LOWER) { res = calculateProfitGameType1(_betNum, betValueInGwei); } else if (_gameType == DICE_HIGHER) { res = calculateProfitGameType2(_betNum, betValueInGwei); } else { assert(false); } return res * 1e9; // convert to wei } /** * Calculate player profit from total won. * @param _totalWon player winning in gwei. * @return player profit in gwei. */ function calcProfitFromTotalWon(uint _totalWon, uint _betValue) private pure returns(int) { // safe to multiply as _totalWon range is fixed. uint houseEdgeValue = _totalWon * HOUSE_EDGE / HOUSE_EDGE_DIVISOR; // safe to cast as all value ranges are fixed return int(_totalWon) - int(houseEdgeValue) - int(_betValue); } /** * @dev Calculate player profit if player has won for game type 1 (dice lower wins). * @param _betNum Bet number of player. * @param _betValue Value of bet in gwei. * @return Players' profit. */ function calculateProfitGameType1(uint _betNum, uint _betValue) private pure returns(int) { assert(_betNum > 0 && _betNum < DICE_RANGE); // safe as ranges are fixed uint totalWon = _betValue * DICE_RANGE / _betNum; return calcProfitFromTotalWon(totalWon, _betValue); } /** * @dev Calculate player profit if player has won for game type 2 (dice lower wins). * @param _betNum Bet number of player. * @param _betValue Value of bet in gwei. * @return Players' profit. */ function calculateProfitGameType2(uint _betNum, uint _betValue) private pure returns(int) { assert(_betNum >= 0 && _betNum < DICE_RANGE - 1); // safe as ranges are fixed uint totalWon = _betValue * DICE_RANGE / (DICE_RANGE - _betNum - 1); return calcProfitFromTotalWon(totalWon, _betValue); } /** * @dev Check if player hash won or lost. * @return true if player has won. */ function hasPlayerWon( uint8 _gameType, uint _betNum, bytes32 _serverSeed, bytes32 _playerSeed ) private pure returns(bool) { bytes32 combinedHash = keccak256(_serverSeed, _playerSeed); uint randNum = uint(combinedHash); if (_gameType == 1) { return calculateWinnerGameType1(randNum, _betNum); } else if (_gameType == 2) { return calculateWinnerGameType2(randNum, _betNum); } else { assert(false); } } /** * @dev Calculate winner of game type 1 (roll lower). * @param _randomNum 256 bit random number. * @param _betNum Bet number. * @return True if player has won false if he lost. */ function calculateWinnerGameType1(uint _randomNum, uint _betNum) private pure returns(bool) { assert(_betNum > 0 && _betNum < DICE_RANGE); uint resultNum = _randomNum % DICE_RANGE; // bias is negligible return resultNum < _betNum; } /** * @dev Calculate winner of game type 2 (roll higher). * @param _randomNum 256 bit random number. * @param _betNum Bet number. * @return True if player has won false if he lost. */ function calculateWinnerGameType2(uint _randomNum, uint _betNum) private pure returns(bool) { assert(_betNum >= 0 && _betNum < DICE_RANGE - 1); uint resultNum = _randomNum % DICE_RANGE; // bias is negligible return resultNum > _betNum; } } library MathUtil { /** * @dev Returns the absolute value of _val. * @param _val value * @return The absolute value of _val. */ function abs(int _val) internal pure returns(uint) { if (_val < 0) { return uint(-_val); } else { return uint(_val); } } /** * @dev Calculate maximum. */ function max(uint _val1, uint _val2) internal pure returns(uint) { return _val1 >= _val2 ? _val1 : _val2; } /** * @dev Calculate minimum. */ function min(uint _val1, uint _val2) internal pure returns(uint) { return _val1 <= _val2 ? _val1 : _val2; } }
Check if player hash won or lost. return true if player has won./
function hasPlayerWon( uint8 _gameType, uint _betNum, bytes32 _serverSeed, bytes32 _playerSeed ) private pure returns(bool) { bytes32 combinedHash = keccak256(_serverSeed, _playerSeed); uint randNum = uint(combinedHash); if (_gameType == 1) { return calculateWinnerGameType1(randNum, _betNum); return calculateWinnerGameType2(randNum, _betNum); assert(false); } }
421,042
./full_match/1/0xC4bfcAC43433C2435184c87aF26daDE9379b5B11/sources/project:/contracts/MtrollerUser.sol
Returns whether the given account is entered in the given asset account The address of the account to check mToken The mToken to check return True if the account is in the asset, otherwise false./
function accountMembership(uint240 mToken, address account) internal view returns (bool) { return markets[mToken]._accountMembership[account]; }
4,993,198
./partial_match/80001/0x5c653357289333a22AF4c4b4DD61d930ACdA09A0/sources/contracts/upgradeable/XPassportV1.sol
Add new passport info field to `passportInfoFields` newInfo unique name of the data field of the value such as `id`, `name`, `address`, `description`, and etc.
function addPassportInfo(string calldata newInfo) public onlyAdmin { bool passportInfoExists = isPassportInfoExists(newInfo); if (!passportInfoExists) { passportInfoFields.push(newInfo); emit AddPassportInfo(newInfo); } }
8,799,468
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/Consideration.sol
Fulfill an order with an arbitrary number of items for offer and consideration. Note that this function does not support criteria-based orders or partial filling of orders (though filling the remainder of a partially-filled order is supported). @custom:param order The order to fulfill. Note that both the offerer and the fulfiller must first approve this contract (or the corresponding conduit if indicated) to transfer any relevant tokens on their behalf and that contracts must implement `onERC1155Received` to receive ERC1155 tokens as consideration. fulfillerConduitKey A bytes32 value indicating what conduit, if any, to source the fulfiller's token approvals from. The zero hash signifies that no conduit should be used (and direct approvals set on this contract). return fulfilled A boolean indicating whether the order has been successfully fulfilled./ @custom:name order/ Convert order to "advanced" order, then validate and fulfill it.
function fulfillOrder( Order calldata, bytes32 fulfillerConduitKey ) external payable override returns (bool fulfilled) { fulfilled = _validateAndFulfillAdvancedOrder( _toAdvancedOrderReturnType(_decodeOrderAsAdvancedOrder)( CalldataStart.pptr() ), fulfillerConduitKey, msg.sender ); }
4,300,794
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import './openzeppelin-solidity/contracts/SafeMath.sol'; import './openzeppelin-solidity/contracts/Ownable.sol'; import './openzeppelin-solidity/contracts/ERC20/SafeERC20.sol'; //Libraries import "./libraries/TxDataUtils.sol"; //Interfaces import "./interfaces/IExternalStorage.sol"; import "./interfaces/IUsers.sol"; contract ExternalStorage is IExternalStorage, TxDataUtils, Ownable { using SafeERC20 for IERC20; IUsers public immutable users; bytes32[] public attributeNames; IERC20 public feeToken; address public feeRecipient; address public operator; // User ERC1155 contract mapping(bytes32 => Attribute) public attributes; //Data storage //Maps from attribute name => NFT ID => data mapping(bytes32 => mapping (uint => uint)) internal uintStorage; mapping(bytes32 => mapping (uint => bool)) internal boolStorage; mapping(bytes32 => mapping (uint => address)) internal addressStorage; mapping(bytes32 => mapping (uint => bytes32)) internal bytes32Storage; mapping(bytes32 => mapping (uint => string)) internal stringStorage; //Used for checking if an attribute's value is unique //Maps from attribute name => data => NFT ID mapping(bytes32 => mapping (bytes => uint)) internal bytesData; constructor(address _feeToken, address _feeRecipient, address _users) Ownable() { require(_feeToken != address(0), "ExternalStorage: Invalid fee token."); require(_feeRecipient != address(0), "ExternalStorage: Invalid fee recipient."); feeToken = IERC20(_feeToken); feeRecipient = _feeRecipient; users = IUsers(_users); } /* ========== VIEWS ========== */ /** * @dev Given the name of an attribute, returns the attribute's variable type * @param _attributeName Name of the attribute * @return (string, uint) The attribute's variable type and update fee */ function getAttribute(bytes32 _attributeName) external view override isValidAttributeName(_attributeName) returns (bytes32, uint) { return (attributes[_attributeName].variableType, attributes[_attributeName].updateFee); } /** * @dev Returns the name, variable type, and update fee for each attribute * @return (bytes32[], bytes32[], uint[]) The name, variable type, and update fee of each attribute */ function getAttributes() external view override returns (bytes32[] memory, bytes32[] memory, uint[] memory) { bytes32[] memory names = attributeNames; bytes32[] memory types = new bytes32[](names.length); uint[] memory fees = new uint[](names.length); for (uint i = 0; i < names.length; i++) { types[i] = attributes[attributeNames[i]].variableType; fees[i] = attributes[attributeNames[i]].updateFee; } return (names, types, fees); } /** * @dev Returns the bytes data and variable type of an attribute * @dev The calling function needs to parse the bytes data based on the variable type * @param _id NFT id * @param _attributeName Name of the attribute * @return (bytes, bytes32) Bytes data of the attribute and the attribute's variable type */ function getValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bytes memory, bytes32) { bytes32 variableType = attributes[_attributeName].variableType; bytes memory rawBytes; if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("uint"))) { rawBytes = abi.encodePacked(uintStorage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("bool"))) { rawBytes = abi.encodePacked(boolStorage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("address"))) { rawBytes = abi.encodePacked(addressStorage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("bytes32"))) { rawBytes = abi.encodePacked(bytes32Storage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("string"))) { rawBytes = bytes(stringStorage[_attributeName][_id]); } return (rawBytes, variableType); } /** * @dev Returns the attribute's value as a uint * @dev Reverts if the attribute is not found or if the attribute doesn't have uint type * @param _id NFT id * @param _attributeName Name of the attribute * @return (uint) Value of the attribute */ function getUintValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (uint) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("uint")), "ExternalStorage: Expected uint type."); return uintStorage[_attributeName][_id]; } /** * @dev Returns the attribute's value as a bool * @dev Reverts if the attribute is not found or if the attribute doesn't have bool type * @param _id NFT id * @param _attributeName Name of the attribute * @return (bool) Value of the attribute */ function getBoolValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bool) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("bool")), "ExternalStorage: Expected bool type."); return boolStorage[_attributeName][_id]; } /** * @dev Returns the attribute's value as a bytes32 * @dev Reverts if the attribute is not found or if the attribute doesn't have bytes32 type * @param _id NFT id * @param _attributeName Name of the attribute * @return (bytes32) Value of the attribute */ function getBytes32Value(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bytes32) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("bytes32")), "ExternalStorage: Expected bytes32 type."); return bytes32Storage[_attributeName][_id]; } /** * @dev Returns the attribute's value as an address * @dev Reverts if the attribute is not found or if the attribute doesn't have address type * @param _id NFT id * @param _attributeName Name of the attribute * @return (address) Value of the attribute */ function getAddressValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (address) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("address")), "ExternalStorage: Expected address type."); return addressStorage[_attributeName][_id]; } /** * @dev Returns the attribute's value as a string * @dev Reverts if the attribute is not found or if the attribute doesn't have string type * @param _id NFT id * @param _attributeName Name of the attribute * @return (string) Value of the attribute */ function getStringValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (string memory) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("string")), "ExternalStorage: Expected string type."); return stringStorage[_attributeName][_id]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Adds an attribute to the Template * @param _attributeName Name of the attribute to add * @param _attributeType The variable type of the attribute * @param _updateFee Fee that a user pays when updating an attribute * @param _canModify Whether the attribute value can be modified after it is initialized. * @return (bool) Whether the attribute was added successfully */ function addAttribute(bytes32 _attributeName, bytes32 _attributeType, uint _updateFee, bool _unique, bool _canModify) external override onlyOwner returns (bool) { if (attributes[_attributeName].name == _attributeName) { return false; } attributes[_attributeName] = Attribute(_unique, _canModify, _updateFee, _attributeName, _attributeType); attributeNames.push(_attributeName); return true; } /** * @dev Adds multiple attributes to the Template * @param _attributeNames Names of the attributes to add * @param _attributeTypes The variable types of the attributes * @param _updateFees Fee that a user pays when updating each attribute * @param _unique Whether the attribute values must be unique throughout a Template * @param _canModify Whether the attribute values can be modified after they are initialized. * @return (bool) Whether the attributes were added successfully */ function addAttributes(bytes32[] calldata _attributeNames, bytes32[] calldata _attributeTypes, uint[] calldata _updateFees, bool[] calldata _unique, bool[] calldata _canModify) external override onlyOwner returns (bool) { if (_attributeNames.length != _attributeTypes.length) { return false; } if (_attributeNames.length != _updateFees.length) { return false; } if (_attributeNames.length != _unique.length) { return false; } for (uint i = 0; i < _attributeNames.length; i++) { if (attributes[_attributeNames[i]].name == _attributeNames[i]) { return false; } attributes[_attributeNames[i]] = Attribute(_unique[i], _canModify[i], _updateFees[i], _attributeNames[i], _attributeTypes[i]); attributeNames.push(_attributeNames[i]); } emit AddedAttributes(_attributeNames, _attributeTypes, _updateFees, _unique); return true; } /** * @dev Sets the attribute's updateFee to the new fee * @param _attributeName Name of the attribute to add * @param _newFee The new updateFee * @return (bool) Whether the fee was updated successfully */ function updateAttributeFee(bytes32 _attributeName, uint _newFee) external override onlyOwner returns (bool) { if (attributes[_attributeName].name != _attributeName) { return false; } if (_newFee < 0) { return false; } attributes[_attributeName].updateFee = _newFee; emit UpdatedAttributeFee(_attributeName, _newFee); return true; } /** * @dev Initializes an attribute to the given value; avoids paying the updateFee * @param _id NFT id * @param _attributeName Name of the attribute * @param _initialValue Initial value of the attribute * @return (bool) Whether the attribute was initialized successfully */ function initializeValue(uint _id, bytes32 _attributeName, bytes calldata _initialValue) external override onlyOperator returns (bool) { if (attributes[_attributeName].name != _attributeName) { return false; } if (_id == 0) { return false; } //Check if attribute value already exists if (attributes[_attributeName].unique && bytesData[_attributeName][_initialValue] > 0) { return false; } return _setValueByType(_id, _attributeName, attributes[_attributeName].variableType, _initialValue); } /** * @dev Initializes multiple attributes * @param _id NFT id * @param _attributeNames Name of the attributes * @param _initialValues Initial values of the attributes * @return (bool) Whether the attributes were initialized successfully */ function initializeValues(uint _id, bytes32[] calldata _attributeNames, bytes[] calldata _initialValues) external override onlyOperator returns (bool) { if (_id == 0) { return false; } for (uint i = 0; i < _attributeNames.length; i++) { if (attributes[_attributeNames[i]].name != _attributeNames[i]) { return false; } //Check if attribute value is unique if (attributes[_attributeNames[i]].unique && bytesData[_attributeNames[i]][_initialValues[i]] > 0) { return false; } if (!_setValueByType(_id, _attributeNames[i], attributes[_attributeNames[i]].variableType, _initialValues[i])) { return false; } } return true; } /** * @dev Sets the attribute's value to the new value * @param _attributeName Name of the attribute * @param _newValue New value of the attribute */ function updateValue(bytes32 _attributeName, bytes calldata _newValue) external override { uint id = users.getUser(msg.sender); require(id > 0, "ExternalStorage: user has not created a profile yet."); require(!attributes[_attributeName].canModify, "ExternalStorage: attribute cannot be modified."); require(attributes[_attributeName].name == _attributeName, "ExternalStorage: attribute does not exist."); require(!(attributes[_attributeName].unique && bytesData[_attributeName][_newValue] > 0), "ExternalStorage: attribute must have a unique value."); // Pay fee for updating attribute value. feeToken.safeTransferFrom(msg.sender, feeRecipient, attributes[_attributeName].updateFee); require(_setValueByType(id, _attributeName, attributes[_attributeName].variableType, _newValue), "ExternalStorage: error when updating value."); emit UpdatedValue(msg.sender, id, _attributeName, _newValue); } /* ========== INTERNAL FUNCTIONS ========== */ function _setValueByType(uint _id, bytes32 _attributeName, bytes32 _variableType, bytes calldata _newValue) internal returns (bool) { //Check if value already exists if (attributes[_attributeName].unique && bytesData[_attributeName][_newValue] > 0) { return false; } else { bytesData[_attributeName][_newValue] = _id; } if (keccak256(abi.encodePacked(_variableType)) == keccak256("uint")) { uintStorage[_attributeName][_id] = uint(read32(_newValue, 0, 32)); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("bool")) { boolStorage[_attributeName][_id] = !(uint(read32(_newValue, 0, 32)) == 0); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("address")) { addressStorage[_attributeName][_id] = convert32toAddress(read32(_newValue, 0, 32)); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("bytes32")) { bytes32Storage[_attributeName][_id] = read32(_newValue, 0, 32); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("string")) { stringStorage[_attributeName][_id] = string(_newValue); } else { return false; } emit SetAttributeValue(_attributeName, _variableType, _newValue); return true; } /* ========== RESTRICTED FUNCTIONS ========== */ function setOperator(address _operator) external onlyOwner operatorNotSet { require(_operator != address(0), "ExternalStorage: invalid operator address."); operator = _operator; emit SetOperator(_operator); } function setAttributeMutability(bytes32 _attributeName, bool _canModify) external onlyOwner isValidAttributeName(_attributeName) { attributes[_attributeName].canModify = _canModify; emit UpdatedAttributeMutability(_attributeName, _canModify); } /* ========== MODIFIERS ========== */ modifier operatorNotSet() { require(operator == address(0), "ExternalStorage: operator has already been set."); _; } modifier isValidId(uint _id) { require(_id > 0, "ExternalStorage: Id is not valid"); _; } modifier isValidAttributeName(bytes32 _name) { require(_name == attributes[_name].name, "ExternalStorage: Attribute not found."); _; } modifier onlyOperator() { require(msg.sender == operator, "ExternalStorage: Only operator can call this function."); _; } /* ========== EVENTS ========== */ event AddedAttribute(bytes32 name, bytes32 variableType, uint updateFee, bool unique); event AddedAttributes(bytes32[] names, bytes32[] variableTypes, uint[] updateFees, bool[] unique); event UpdatedAttributeFee(bytes32 name, uint newFee); event SetAttributeValue(bytes32 name, bytes32 variableType, bytes value); event SetOperator(address operator); event UpdatedValue(address indexed user, uint indexed profileID, bytes32 attributeName, bytes value); event UpdatedAttributeMutability(bytes32 attributeName, bool canModify); }
Given the name of an attribute, returns the attribute's variable type _attributeName Name of the attribute return (string, uint) The attribute's variable type and update fee/
function getAttribute(bytes32 _attributeName) external view override isValidAttributeName(_attributeName) returns (bytes32, uint) { return (attributes[_attributeName].variableType, attributes[_attributeName].updateFee); }
1,769,564
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IRift.sol"; /// @title Mana (for Adventurers) /// @notice This contract mints Mana for Crystals /// @custom:unaudited This contract has not been audited. Use at your own risk. contract Mana is Context, Ownable, ERC20 { event MintMana(address indexed recipient, uint256 amount); // a mapping from an address to whether or not it can mint / burn mapping(address => bool) mintControllers; mapping(address => bool) burnControllers; IERC721Enumerable public crystalsContract; IRift public iRift; constructor() Ownable() ERC20("Adventure Mana", "AMNA") { _mint(_msgSender(), 1000000); } function ownerSetRift(address rift) public onlyOwner { iRift = IRift(rift); } /// @notice function for Crystals contract to mint on behalf of to /// @param recipient address to send mana to /// @param amount number of mana to mint function ccMintTo(address recipient, uint256 amount) external { // Check that the msgSender is from Crystals require(mintControllers[msg.sender], "Only controllers can mint"); _mint(recipient, amount); emit MintMana(recipient, amount); } function burn(address from, uint256 amount) external { require(burnControllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } /** * enables an address to mint * @param controller the address to enable */ function addMintController(address controller) external onlyOwner { mintControllers[controller] = true; } /** * disables an address from minting * @param controller the address to disbale */ function removeMintController(address controller) external onlyOwner { mintControllers[controller] = false; } /** * enables an address to burn * @param controller the address to enable */ function addBurnController(address controller) external onlyOwner { burnControllers[controller] = true; } /** * disables an address from burning * @param controller the address to disbale */ function removeBurnController(address controller) external onlyOwner { burnControllers[controller] = false; } function decimals() public pure override returns (uint8) { return 0; } } /* ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌ ▐░█▀▀▀▀█░█▀▀ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀ by chris and tony */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; struct RiftBag { uint16 charges; uint32 chargesUsed; uint16 level; uint64 xp; uint64 lastChargePurchase; } interface IRiftData { function bags(uint256 bagId) external view returns (RiftBag memory); function addCharges(uint16 charges, uint256 bagId) external; function removeCharges(uint16 charges, uint256 bagId) external; function updateLevel(uint16 level, uint256 bagId) external; function updateXP(uint64 xp, uint256 bagId) external; function addKarma(uint64 k, address holder) external; function removeKarma(uint64 k, address holder) external; function updateLastChargePurchase(uint64 time, uint256 bagId) external; function karma(address holder) external view returns (uint64); function karmaTotal() external view returns (uint256); function karmaHolders() external view returns (uint256); } /* Logic free storage of Rift Data. The intent of this storage is twofold: 1. The data manipulation performed by the Rift is novel (especially to the authors), and this store acts as a failsafe in case a new Rift contract needs to be deployed. 2. The authors' intent is to grant control of this data to more controllers (a DAO, L2 rollup, etc). */ contract RiftData is IRiftData, OwnableUpgradeable { mapping(address => bool) public riftControllers; uint256 public karmaTotal; uint256 public karmaHolders; mapping(uint256 => RiftBag) internal _bags; mapping(address => uint64) public karma; function initialize() public initializer { __Ownable_init(); } function addRiftController(address addr) external onlyOwner { riftControllers[addr] = true; } function removeRiftController(address addr) external onlyOwner { riftControllers[addr] = false; } modifier onlyRiftController() { require(riftControllers[msg.sender], "NO!"); _; } function bags(uint256 bagId) external view override returns (RiftBag memory) { return _bags[bagId]; } function getBags(uint256[] calldata bagIds) external view returns (RiftBag[] memory output) { for(uint256 i = 0; i < bagIds.length; i++) { output[i] = _bags[bagIds[i]]; } return output; } function addCharges(uint16 charges, uint256 bagId) external override onlyRiftController { _bags[bagId].charges += charges; } function removeCharges(uint16 charges, uint256 bagId) external override onlyRiftController { require(_bags[bagId].charges >= charges, "Not enough charges"); _bags[bagId].charges -= charges; _bags[bagId].chargesUsed += charges; } function updateLevel(uint16 level, uint256 bagId) external override onlyRiftController { _bags[bagId].level = level; } function updateXP(uint64 xp, uint256 bagId) external override onlyRiftController { _bags[bagId].xp = xp; } function addKarma(uint64 k, address holder) external override onlyRiftController { if (karma[holder] == 0) { karmaHolders += 1; } karmaTotal += k; karma[holder] += k; } function removeKarma(uint64 k, address holder) external override onlyRiftController { k > karma[holder] ? karma[holder] = 0 : karma[holder] -= k; } function updateLastChargePurchase(uint64 time, uint256 bagId) external override onlyRiftController { _bags[bagId].lastChargePurchase = time; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./RiftData.sol"; interface IRift { function riftLevel() external view returns (uint32); function setupNewBag(uint256 bagId) external; function useCharge(uint16 amount, uint256 bagId, address from) external; function bags(uint256 bagId) external view returns (RiftBag memory); function awardXP(uint32 bagId, uint16 xp) external; function isBagHolder(uint256 bagId, address owner) external; } struct BagProgress { uint32 lastCompletedStep; bool completedQuest; } struct BurnableObject { uint64 power; uint32 mana; uint16 xp; } interface IRiftBurnable { function burnObject(uint256 tokenId) external view returns (BurnableObject memory); } interface IMana { function ccMintTo(address recipient, uint256 amount) external; function burn(address from, uint256 amount) 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; 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 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; /** * @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; /** * @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; 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; 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 "../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; /** * @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 "../../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; 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 "../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); } // SPDX-License-Identifier: MIT 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 { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT 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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { 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; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; } 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 { __Context_init_unchained(); __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()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; }
enables an address to mint controller the address to enable/
function addMintController(address controller) external onlyOwner { mintControllers[controller] = true; }
1,136,629
//SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./extensions/ERC721EnumerableForOwner.sol"; import "./extensions/IWETH.sol"; /* * @title Pools that incentivise long term holding with bonus and penalty mechanisms * for any ERC20 token (or ETH) deposit. * Each asset has one independent pool within the contract. * Bonuses are funded from the penalties for early withdrawals. * There are two bonus types for each pool - holding bonus (to incentivise holding), * and commitment bonus (to incentivise commiting to penalties & time). * The initial penalty and commitment time are chosen at the time of the deposit by * the user. * The deposits into this contract are transferrable and immutable ERC721 tokens. * ERC20 tokens may have fee-on-transfer or dynamic supply mechanisms, and for these * kinds of tokens this contract tracks everything as "shares of initial deposits". * @notice The mechanism rules: * - A depositor is committing for "commitment period" and an "initial penalty percent" * of his choice (within allowed ranges). After the commitment period the * deposit can be withdrawn with its share of both of the bonus pools. * - The two bonus pools are populated from the penalties for early withdrawals, * which are withdrawals done before a deposit's commitment period is elapsed. * - The penalties are split in half and added to both bonus pools (isolated per asset): * Hold bonus pool and Commit bonus pool. * - The share of the bonus pools is equal to the share of the bonus points (hold-points * and commit-points) for the deposit at the time of withdrawal relative to the other * deposits in the pool. * - Hold points are calculated as amount of asset x seconds held. So more tokens * held for longer add more points - and increase the bonus share. This bonus is * independent of commitment or penalties. The points keep increasing after commitment period * is over. * - Commit points are calculated as amount of asset x seconds committed to penalty. * These points depend only on commitment time and commitment penalty * at the time of the deposit. * - Withdrawal before commitment period is not entitled to any part of the bonus * and is instead "slashed" with a penalty (that is split between the bonuses pools). * - The penalty percent is decreasing with time from the chosen * initialPenaltyPercent to 0 at the end of the commitPeriod. * - Each deposit has a separate ERC721 tokenId with the usual tranfer mechanics. So * multiple deposits for same owner and asset but with different commitment * parameters can co-exist independently. * - Deposits can be deposited for another account as beneficiary, * so e.g. a team / DAO can deposit its tokens for its members to withdraw. * - Only the deposit "owner" can use the withdrawal functionality, so ERC721 approvals * allow transfers, but not withdrawals. * * @dev * 1. For safety and clarity, withdrawal functionality is split into * two methods, one for withdrawing with penalty, and the other one for withdrawing * with bonus. * 2. ERC20 token and ETH functionality is split into separate methods. * 3. Deposit for msg.sender and depositFor are split into separate methods * for clarity. * 4. For tokens with dynamic supply mechanisms and fee on transfer all internal * calculations are done using the "initial desposit amounts" as fair shares, and * upon withdrawal are translated to actual amounts of the contract's token balance. * This means that for these tokens the actual amounts received are depends on their * mechanisms (because the amount is unknowable before actual transfers). * 5. To reduce RPC calls and simplify interface, all the deposit and pool views are * batched in depositDetails and poolDetails which return arrays of values. * 6. To prevent relying on events tracking depositsOfOwner view shows all * deposits owned by a particular owner. * 7. The total of a pool's hold points are updated incrementally on each transaction * with a pool using the depositsSum in that pool for that period. * 8. TokenURI returns a JSON string with basic name and description for the deposit. * * @author artdgn (@github) */ contract HodlPoolV3 is ERC721EnumerableForOwner { using SafeERC20 for IERC20; using Strings for uint; /// @dev state variables for a deposit in a pool struct Deposit { address asset; uint40 time; uint16 initialPenaltyPercent; uint40 commitPeriod; uint amount; } /// @dev state variables for a token pool struct Pool { uint depositsSum; // sum of all current deposits uint holdBonusesSum; // sum of hold bonus pool uint commitBonusesSum; // sum of commit bonus pool uint totalHoldPoints; // sum of hold-points uint totalHoldPointsUpdateTime; // time of the latest hold-points update uint totalCommitPoints; // sum of commit-points } /// @notice minimum initial percent of penalty uint public immutable minInitialPenaltyPercent; /// @notice minimum commitment period for a deposit uint public immutable minCommitPeriod; /// @notice compatibility with ERC20 for e.g. viewing in metamask uint public constant decimals = 0; /// @notice WETH token contract this pool is using for handling ETH // slither-disable-next-line naming-convention address public immutable WETH; /// @dev tokenId incremted counter uint internal nextTokenId = 1; /// @dev deposit data for each tokenId mapping(uint => Deposit) deposits; /// @dev pool state for each token contract address /// default values are all zeros, no need to init // slither-disable-next-line uninitialized-state mapping(address => Pool) pools; /* * @param asset ERC20 token address for the deposited asset * @param account address that has made the deposit * @param amount size of new deposit, or deposit increase * @param amountReceived received balance after transfer (actual deposit) * which may be different due to transfer-fees and other token shenanigans * @param time timestamp from which the commitment period will be counted * @param initialPenaltyPercent initial penalty percent for the deposit * @param commitPeriod commitment period in seconds for the deposit * @param tokenId deposit ERC721 tokenId */ event Deposited( address indexed asset, address indexed account, uint amount, uint amountReceived, uint time, uint initialPenaltyPercent, uint commitPeriod, uint tokenId ); /* * @param asset ERC20 token address for the withdrawed asset * @param account address that has made the withdrawal * @param amount amount sent out to account as withdrawal * @param depositAmount the original amount deposited * @param penalty the penalty incurred for this withdrawal * @param holdBonus the hold-bonus included in this withdrawal * @param commitBonus the commit-bonus included in this withdrawal * @param timeHeld the time in seconds the deposit was held */ event Withdrawed( address indexed asset, address indexed account, uint amount, uint depositAmount, uint penalty, uint holdBonus, uint commitBonus, uint timeHeld ); /// @dev checks commitment params are within allowed ranges modifier validCommitment(uint initialPenaltyPercent, uint commitPeriod) { require(initialPenaltyPercent >= minInitialPenaltyPercent, "penalty too small"); require(initialPenaltyPercent <= 100, "initial penalty > 100%"); require(commitPeriod >= minCommitPeriod, "commitment period too short"); require(commitPeriod <= 4 * 365 days, "commitment period too long"); _; } /* * @param _minInitialPenaltyPercent the minimum penalty percent for deposits * @param _minCommitPeriod the minimum time in seconds for commitPeriod of a deposit * @param _WETH wrapped ETH contract address this pool will be using for ETH */ constructor ( uint _minInitialPenaltyPercent, uint _minCommitPeriod, address _WETH ) ERC721("HodlBonusPool V3", "HodlPoolV3") { require(_minInitialPenaltyPercent > 0, "no min penalty"); require(_minInitialPenaltyPercent <= 100, "minimum initial penalty > 100%"); require(_minCommitPeriod >= 10 seconds, "minimum commitment period too short"); require(_minCommitPeriod <= 4 * 365 days, "minimum commitment period too long"); require(_WETH != address(0), "WETH address can't be 0x0"); minInitialPenaltyPercent = _minInitialPenaltyPercent; minCommitPeriod = _minCommitPeriod; WETH = _WETH; } /// @notice contract doesn't support sending ETH directly receive() external payable { require( msg.sender == WETH, "no receive() except from WETH contract, use depositETH()"); } /* * * * * * * * * * * * * Public transactions * * * * * * * * * * * * */ /* * @notice adds a deposit into its asset pool and mints an ERC721 token * @param asset address of ERC20 token contract * @param amount of token to deposit * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function deposit( address asset, uint amount, uint initialPenaltyPercent, uint commitPeriod ) public validCommitment(initialPenaltyPercent, commitPeriod) returns (uint tokenId) { require(amount > 0, "empty deposit"); // interal accounting update tokenId = _depositAndMint( asset, msg.sender, amount, initialPenaltyPercent, commitPeriod ); // this contract's balance before the transfer uint beforeBalance = IERC20(asset).balanceOf(address(this)); // transfer IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); // what was actually received, this amount is only used in the event and // not used for any internal accounting so reentrancy from transfer is not // a substantial risk uint amountReceived = IERC20(asset).balanceOf(address(this)) - beforeBalance; // because we want to know how much was received, reentrancy-*events* is low-risk // slither-disable-next-line reentrancy-events emit Deposited( asset, msg.sender, amount, amountReceived, block.timestamp, initialPenaltyPercent, commitPeriod, tokenId ); } /* * @notice payable method for depositing ETH with same logic as deposit(), * adds a deposit into WETH asset pool and mints an ERC721 token * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function depositETH( uint initialPenaltyPercent, uint commitPeriod ) public validCommitment(initialPenaltyPercent, commitPeriod) payable returns (uint tokenId) { require(msg.value > 0, "empty deposit"); // interal accounting update tokenId = _depositAndMint( WETH, msg.sender, msg.value, initialPenaltyPercent, commitPeriod ); emit Deposited( WETH, msg.sender, msg.value, msg.value, block.timestamp, initialPenaltyPercent, commitPeriod, tokenId ); // note: no share vs. balance accounting for WETH because it's assumed to // exactly correspond to actual deposits and withdrawals (no fee-on-transfer etc) IWETH(WETH).deposit{value: msg.value}(); } /* * @notice adds a deposit, mints an ERC721 token, and transfers * its ownership to another account * @param account that will be the owner of this deposit (can withdraw) * @param asset address of ERC20 token contract * @param amount of token to deposit * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function depositFor( address account, address asset, uint amount, uint initialPenaltyPercent, uint commitPeriod ) external validCommitment(initialPenaltyPercent, commitPeriod) returns (uint tokenId) { tokenId = deposit(asset, amount, initialPenaltyPercent, commitPeriod); _transfer(msg.sender, account, tokenId); } /* * @notice adds an ETH deposit, mints an ERC721 token, and transfers * its ownership to another account * @param account that will be the owner of this deposit (can withdraw) * @param initialPenaltyPercent initial penalty percent for deposit * @param commitPeriod period during which a withdrawal results in penalty and no bonus * @return ERC721 tokenId of this deposit */ function depositETHFor( address account, uint initialPenaltyPercent, uint commitPeriod ) external payable validCommitment(initialPenaltyPercent, commitPeriod) returns (uint tokenId) { tokenId = depositETH(initialPenaltyPercent, commitPeriod); _transfer(msg.sender, account, tokenId); } /* * @param tokenId ERC721 tokenId of the deposit to withdraw * @notice withdraw the full deposit with the proportional shares of bonus pools. * will fail for early withdawals (for which there is another method) * @dev checks that the deposit is non-zero */ function withdrawWithBonus(uint tokenId) external { require( _timeLeft(deposits[tokenId]) == 0, "cannot withdraw without penalty yet, use withdrawWithPenalty()" ); _withdrawERC20(tokenId); } /// @notice withdraw ETH with bonus with same logic as withdrawWithBonus() function withdrawWithBonusETH(uint tokenId) external { require( _timeLeft(deposits[tokenId]) == 0, "cannot withdraw without penalty yet, use withdrawWithPenaltyETH()" ); _withdrawETH(tokenId); } /* * @param tokenId ERC721 tokenId of the deposit to withdraw * @notice withdraw the deposit with any applicable penalty. Will withdraw * with any available bonus if penalty is 0 (commitment period elapsed). */ function withdrawWithPenalty(uint tokenId) external { _withdrawERC20(tokenId); } /// @notice withdraw ETH with penalty with same logic as withdrawWithPenalty() function withdrawWithPenaltyETH(uint tokenId) external { _withdrawETH(tokenId); } /* * * * * * * * * * Public views * * * * * * * * * */ /* * @param tokenId ERC721 tokenId of a deposit * @return array of 12 values corresponding to the details of the deposit: * 0. asset - asset address converted to uint * 1. owner - deposit owner * 2. balance - original deposit(s) value * 3. timeLeftToHold - time in seconds until deposit can be withdrawed * with bonus and no penalty * 4. penalty - penalty if withdrawed now * 5. holdBonus - hold-bonus if withdrawed now (if possible to withdraw with bonus) * 6. commitBonus - commit-bonus if withdrawed now (if possible to withdraw with bonus) * 7. holdPoints - current amount of hold-point * 8. commitPoints - current amount of commit-point * 9. initialPenaltyPercent - initial penalty percent (set at time od deposit) * 10. currentPenaltyPercent - current penalty percent (penalty percent if withdrawed now) * 11. commitPeriod - commitment period set at the time of deposit */ function depositDetails( uint tokenId ) external view returns (uint[12] memory) { Deposit storage dep = deposits[tokenId]; Pool storage pool = pools[dep.asset]; address owner = _exists(tokenId) ? ownerOf(tokenId) : address(0); return [ uint(uint160(dep.asset)), // asset uint(uint160(owner)), // account owner _sharesToAmount(dep.asset, dep.amount), // balance _timeLeft(dep), // timeLeftToHold _sharesToAmount(dep.asset, _depositPenalty(dep)), // penalty _sharesToAmount(dep.asset, _holdBonus(pool, dep)), // holdBonus _sharesToAmount(dep.asset, _commitBonus(pool, dep)), // commitBonus _holdPoints(dep), // holdPoints _commitPoints(dep), // commitPoints dep.initialPenaltyPercent, // initialPenaltyPercent _currentPenaltyPercent(dep), // currentPenaltyPercent dep.commitPeriod // commitPeriod ]; } /* * @param asset address of ERC20 token contract * @return array of 5 values corresponding to the details of the pool: * 0. depositsSum - sum of current deposits * 1. holdBonusesSum - sum of tokens to be distributed as hold bonuses * 2. commitBonusesSum - sum of tokens to be distributed as commitment bonuses * 3. totalHoldPoints - sum of hold-points of all current deposits * 4. totalCommitPoints - sum of commit-points of all current deposits */ function poolDetails(address asset) external view returns (uint[5] memory) { Pool storage pool = pools[asset]; return [ _sharesToAmount(asset, pool.depositsSum), // depositsSum _sharesToAmount(asset, pool.holdBonusesSum), // holdBonusesSum _sharesToAmount(asset, pool.commitBonusesSum), // commitBonusesSum _totalHoldPoints(pool), // totalHoldPoints pool.totalCommitPoints // totalCommitPoints ]; } /* * @param account address of an owner account * @return two arrays of the deposits owned by this account: * 0. array of deposits' tokenIds * 1. array of deposits' data (Deposit struct) */ function depositsOfOwner( address account ) external view returns ( uint[] memory tokenIds, Deposit[] memory accountDeposits ) { uint balance = balanceOf(account); tokenIds = new uint[](balance); accountDeposits = new Deposit[](balance); for (uint i; i < balance; i++) { tokenIds[i] = tokenOfOwnerByIndex(account, i); accountDeposits[i] = deposits[tokenIds[i]]; } } /* * @param tokenId ERC721 tokenId of a deposit * @return string with metadata JSON containing the NFT's name and description */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: nonexistent token"); Deposit storage dep = deposits[tokenId]; return string(abi.encodePacked( '{"name":"Hodl-bonus-pool deposit, tokenId: ', tokenId.toString(), '", "description":"ERC20 asset address: ', (uint(uint160(dep.asset))).toHexString(20), '\\nDeposited amount: ', dep.amount.toString(), ' wei (of token)\\nDeposited at: ', uint(dep.time).toString(), ' seconds unix epoch\\nInitial penalty percent: ', uint(dep.initialPenaltyPercent).toString(), '%\\nCommitment period: ', uint(dep.commitPeriod).toString(), ' seconds"}' )); } /* * * * * * * * * * * * * * Internal transactions * * * * * * * * * * * * * */ /// @dev the order of calculations is important for correct accounting function _depositAndMint( address asset, address account, uint amount, uint initialPenaltyPercent, uint commitPeriod ) internal returns (uint tokenId) { // get token id and increment tokenId = nextTokenId++; // mint token _mint(account, tokenId); // add deposit data deposits[tokenId] = Deposit({ asset: asset, time: uint40(block.timestamp), initialPenaltyPercent: uint16(initialPenaltyPercent), commitPeriod: uint40(commitPeriod), amount: amount }); // pool state update _addDepositToPool(asset, deposits[tokenId]); } /// @dev pool state update for new deposit function _addDepositToPool(address asset, Deposit storage dep) internal { Pool storage pool = pools[asset]; // update pool's total hold time due to passage of time // because the deposits sum is going to change _updatePoolHoldPoints(pool); // WARNING: the deposits sum needs to be updated after the hold-points // for the passed time were updated pool.depositsSum += dep.amount; pool.totalCommitPoints += _commitPoints(dep); } // this happens on every pool interaction (so every withdrawal and deposit to that pool) function _updatePoolHoldPoints(Pool storage pool) internal { // add points proportional to amount held in pool since last update pool.totalHoldPoints = _totalHoldPoints(pool); pool.totalHoldPointsUpdateTime = block.timestamp; } function _withdrawERC20(uint tokenId) internal { address asset = deposits[tokenId].asset; address account = ownerOf(tokenId); require(account == msg.sender, "not deposit owner"); uint amountOut = _amountOutAndBurn(tokenId); // WARNING: asset and account must be set before token is burned IERC20(asset).safeTransfer(account, amountOut); } function _withdrawETH(uint tokenId) internal { address account = ownerOf(tokenId); require(account == msg.sender, "not deposit owner"); require(deposits[tokenId].asset == WETH, "not an ETH / WETH deposit"); uint amountOut = _amountOutAndBurn(tokenId); IWETH(WETH).withdraw(amountOut); // WARNING: account must be set before token is burned // - call is used because if contract is withdrawing it may need more gas than what .transfer sends // slither-disable-next-line low-level-calls (bool success, ) = payable(account).call{value: amountOut}(""); require(success); } /// @dev the order of calculations is important for correct accounting function _amountOutAndBurn(uint tokenId) internal returns (uint amountOut) { // WARNING: deposit is only read here and is not updated until it's removal Deposit storage dep = deposits[tokenId]; address asset = dep.asset; Pool storage pool = pools[asset]; // update pool hold-time points due to passage of time // WARNING: failing to do so will break hold-time holdBonus calculation _updatePoolHoldPoints(pool); // calculate penalty & bunus before making changes uint penalty = _depositPenalty(dep); uint holdBonus = 0; uint commitBonus = 0; uint withdrawShare = dep.amount - penalty; if (penalty == 0) { // only get any bonuses if no penalty holdBonus = _holdBonus(pool, dep); commitBonus = _commitBonus(pool, dep); withdrawShare += holdBonus + commitBonus; } // WARNING: get amount here before state is updated amountOut = _sharesToAmount(asset, withdrawShare); // WARNING: emit event here with all the needed data, before pool state updates // affect shareToAmount calculations emit Withdrawed( asset, ownerOf(tokenId), amountOut, dep.amount, _sharesToAmount(asset, penalty), _sharesToAmount(asset, holdBonus), _sharesToAmount(asset, commitBonus), _timeHeld(dep.time) ); // pool state update // WARNING: shares calculations need to happen before this update // because the depositSum changes _removeDepositFromPool(pool, dep, penalty, holdBonus, commitBonus); // deposit update: remove deposit // WARNING: note that removing the deposit before this line will // change "dep" because it's used by reference and will affect the other // computations for pool state updates (e.g. hold points) delete deposits[tokenId]; // burn token _burn(tokenId); } /// @dev pool state update for removing a deposit function _removeDepositFromPool( Pool storage pool, Deposit storage dep, uint penalty, uint holdBonus, uint commitBonus ) internal { // update total deposits pool.depositsSum -= dep.amount; // remove the acrued hold-points for this deposit pool.totalHoldPoints -= _holdPoints(dep); // remove the commit-points pool.totalCommitPoints -= _commitPoints(dep); if (penalty == 0 && (holdBonus > 0 || commitBonus > 0)) { pool.holdBonusesSum -= holdBonus; // update commitBonus pool pool.commitBonusesSum -= commitBonus; } else { // update hold-bonus pool: split the penalty into two parts // half for hold bonuses, half for commit bonuses pool.holdBonusesSum += penalty / 2; // update commitBonus pool pool.commitBonusesSum += (penalty - (penalty / 2)); } } /* * * * * * * * * * * Internal views * * * * * * * * * * */ function _timeHeld(uint time) internal view returns (uint) { return block.timestamp - time; } function _timeLeft(Deposit storage dep) internal view returns (uint) { uint timeHeld = _timeHeld(dep.time); return (timeHeld >= dep.commitPeriod) ? 0 : (dep.commitPeriod - timeHeld); } function _holdPoints(Deposit storage dep) internal view returns (uint) { // points proportional to amount held since deposit start return dep.amount * _timeHeld(dep.time); } function _commitPoints(Deposit storage dep) internal view returns (uint) { // points proportional to amount held since deposit start // triangle area of commitpent time and penalty return ( dep.amount * dep.initialPenaltyPercent * dep.commitPeriod / 100 / 2 ); } function _currentPenaltyPercent(Deposit storage dep) internal view returns (uint) { uint timeLeft = _timeLeft(dep); if (timeLeft == 0) { // no penalty return 0; } else { // current penalty percent is proportional to time left uint curPercent = (dep.initialPenaltyPercent * timeLeft) / dep.commitPeriod; // add 1 to compensate for rounding down unless when below initial amount return curPercent < dep.initialPenaltyPercent ? curPercent + 1 : curPercent; } } function _depositPenalty(Deposit storage dep) internal view returns (uint) { uint timeLeft = _timeLeft(dep); if (timeLeft == 0) { // no penalty return 0; } else { // order important to prevent rounding to 0 return ( (dep.amount * dep.initialPenaltyPercent * timeLeft) / dep.commitPeriod) // can't be zero / 100; } } function _holdBonus(Pool storage pool, Deposit storage dep) internal view returns (uint) { // share of bonus is proportional to hold-points of this deposit relative // to total hold-points in the pool // order important to prevent rounding to 0 uint denom = _totalHoldPoints(pool); // don't divide by 0 uint holdPoints = _holdPoints(dep); return denom > 0 ? ((pool.holdBonusesSum * holdPoints) / denom) : 0; } function _commitBonus(Pool storage pool, Deposit storage dep) internal view returns (uint) { // share of bonus is proportional to commit-points of this deposit relative // to all other commit-points in the pool // order important to prevent rounding to 0 uint denom = pool.totalCommitPoints; // don't divide by 0 uint commitPoints = _commitPoints(dep); return denom > 0 ? ((pool.commitBonusesSum * commitPoints) / denom) : 0; } function _totalHoldPoints(Pool storage pool) internal view returns (uint) { uint elapsed = block.timestamp - pool.totalHoldPointsUpdateTime; // points proportional to amount held in pool since last update return pool.totalHoldPoints + (pool.depositsSum * elapsed); } /// @dev translates deposit shares to actual token amounts - which can be different /// from the initial deposit amount for tokens with funky fees and supply mechanisms. function _sharesToAmount(address asset, uint share) internal view returns (uint) { if (share == 0) { // gas savings return 0; } // all tokens that belong to this contract are either // in deposits or in the two bonuses pools Pool storage pool = pools[asset]; uint totalShares = pool.depositsSum + pool.holdBonusesSum + pool.commitBonusesSum; if (totalShares == 0) { // don't divide by zero return 0; } else { // it's safe to call external balanceOf here because // it's a view (and this method is also view) uint actualBalance = IERC20(asset).balanceOf(address(this)); return actualBalance * share / totalShares; } } // remove super implementation function _baseURI() internal view virtual override returns (string memory) {} }
share of bonus is proportional to hold-points of this deposit relative to total hold-points in the pool order important to prevent rounding to 0
function _holdBonus(Pool storage pool, Deposit storage dep) internal view returns (uint) { uint holdPoints = _holdPoints(dep); return denom > 0 ? ((pool.holdBonusesSum * holdPoints) / denom) : 0; }
7,269,860
pragma solidity ^0.5.0; /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** CONSTANTS */ /** * @notice Number of positions that the comma is shifted to the right. */ function digits() internal pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Hardcoded to 24 digits. */ function fixed1() internal pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * Hardcoded to 24 digits. */ function mulPrecision() internal pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Hardcoded to 24 digits. */ function maxInt256() internal pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Hardcoded to 24 digits. */ function minInt256() internal pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev Hardcoded to 24 digits. */ function maxNewFixed() internal pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Hardcoded to 24 digits. */ function minNewFixed() internal pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Hardcoded to 24 digits. */ function maxFixedAdd() internal pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Hardcoded to 24 digits. */ function maxFixedSub() internal pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Hardcoded to 24 digits. */ function maxFixedMul() internal pure returns(int256) { return 240615969168004511545033772477625056927114980741063; } /** * @notice Maximum value that can be safely used as a dividend. * @dev Hardcoded to 24 digits. */ function maxFixedDiv() internal pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Hardcoded to 24 digits. */ function maxFixedDivisor() internal pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** CONVERSIONS */ /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) internal pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38, "Too many digits."); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Safe casting from int256 to uint256 * @param x int256 to cast * @return casted uint256 */ function safeIntToUint(int256 x) internal pure returns(uint256) { require( x >= 0, "Cannot cast negative signed integer to unsigned integer." ); return uint256(x); } /** * @notice Safe casting from uint256 to int256 * @param x uint256 to cast * @return casted int256 */ function safeUintToInt(uint256 x) internal pure returns(int256) { require( x <= safeIntToUint(maxInt256()), "Cannot cast overflowing unsigned integer to signed integer." ); return int256(x); } /// @dev Create a Fixidity fixed point number with `digits()` decimal numbers from an fixed point integer created elsewhere. function toFixed(int256 x, uint8 _originDigits) internal pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /// @dev Create a Fixidity fixed point number with `digits()` decimal numbers from an fixed point unsigned integer created elsewhere. /// ERC20Detailed tokens are in a fixed point representation of `decimals()` decimal numbers. /// When working with wei amounts, use `fixedFromUint(amount, token.decimals())`. /// To create decimal numbers, like for example 2.345, you would call `fixedFromUint(2345, 3)`. function toFixed(uint256 x, uint8 _originDigits) internal pure returns (int256) { return toFixed(safeUintToInt(x), _originDigits); } /// @dev Create a Fixidity fixed point number with `digits()` decimal numbers from an integer. function toFixed(int256 x) internal pure returns (int256) { return toFixed(x, 0); } /// @dev Create a Fixidity fixed point number with `digits()` decimal numbers from an unsigned integer. function toFixed(uint256 x) internal pure returns (int256) { return toFixed(x, 0); } /// @dev Convert a Fixidity fixed point number to an integer, truncating decimal numbers less significative than `_destinationDigits` and then removing the comma. function toInt(int256 x, uint8 _destinationDigits) internal pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /// @dev Convert a Fixidity fixed point number to an unsigned integer, truncating decimal numbers less significative than `_destinationDigits` and then removing the comma. /// ERC20Detailed tokens are in a fixed point representation of `decimals()` decimal numbers. /// When working with wei amounts, use `uintFromFixed(amount, token.decimals())`. function toUint(int256 x, uint8 _destinationDigits) internal pure returns (uint256) { return safeIntToUint(toInt(x, _destinationDigits)); } /// @dev Convert a Fixidity fixed point number to an integer, truncating all decimal numbers function toInt(int256 x) internal pure returns (int256) { return toInt(x, 0); } /// @dev Convert a Fixidity fixed point number to an unsigned integer, truncating all decimal numbers function toUint(int256 x) internal pure returns (uint256) { return toUint(x, 0); } /** MATH */ /** * @notice Returns the integer part of a fixed point number. */ function integer(int256 x) internal pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. */ function fractional(int256 x) internal pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the negative of a fixed point number. * Due to int256 having one more negative number than positive numbers * negative(minInt256) reverts. */ function negative(int256 x) internal pure returns (int256) { require(x > minInt256()); return -x; } /** * @notice Converts to positive if negative. */ function abs(int256 x) internal pure returns (int256) { if (x >= 0) { return x; } else { return negative(x); } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. */ function add(int256 x, int256 y) internal pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) require(z > x && z > y); if (x < 0 && y < 0) require(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. */ function subtract(int256 x, int256 y) internal pure returns (int256) { return add(x,negative(y)); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. */ function multiply(int256 x, int256 y) internal pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) require(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) require(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) require(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) require(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) require(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x */ function reciprocal(int256 x) internal pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. */ function divide(int256 x, int256 y) internal pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } /** OBSOLETE FUNCTIONS - LEFT FOR BACKWARDS COMPATIBILITY */ /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). */ function newFixedFraction( int256 numerator, int256 denominator ) internal pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). */ function newFixed(int256 x) internal pure returns (int256) { return newFixed(x, 0); } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) internal pure returns (int256) { return toFixed(x, _originDigits); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) internal pure returns (int256) { return toInt(x, _destinationDigits); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) internal pure returns (int256) { return toInt(x, 0); } }
Create a Fixidity fixed point number with `digits()` decimal numbers from an fixed point integer created elsewhere.
function toFixed(int256 x, uint8 _originDigits) internal pure returns (int256) { return convertFixed(x, _originDigits, digits()); }
12,826,781
./full_match/4/0x7Bd6062a2056Ba6b9775EfF89fdAa507Ba4B9E14/sources/baal.sol
Returns the `fee` to be charged for a flash loan. amount The sum of tokens lent. return fee The `fee` amount of 'token' to be charged for the loan, on top of the returned principal - uniform in Baal.
function flashFee(address, uint256 amount) public view returns (uint256 fee) { fee = (amount * flashFeeNumerator) / 10000; /*Calculate `fee` - precision factor '10000' derived from ERC-3156 'Flash Loan Reference'*/ }
12,297,342
pragma solidity ^0.5.12; // Library & interfaces import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./interface/ICERC20.sol"; // Contracts import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./token/CherryDai.sol"; import "./CherryMath.sol"; /** * @title CherryPool Contract * @notice This contract handle Cherry Pool functionalities */ contract CherryPool is Initializable { using SafeMath for uint256; address public owner; uint256 public poolBalance; // total pool balance in DAI uint256 public poolcBalance; // total pool providers cdai balance cDai uint256 public longPoolBalance; // long pool balance in DAI uint256 public shortPoolBalance; // short pool balance in DAI uint256 public longPoolReserved; // amount of DAI reserved in the long pool uint256 public shortPoolReserved; // amount of DAI reserved in the short pool int256 public poolcTokenProfit; //the total net profit the pool has made in ctokens (or lost) during it life IERC20 public token; // collateral asset = DAI ICERC20 public cToken; // cDAI token CherryDai public cherryDai; // CherryDai token CherryMath cherryMath; // Math library event DepositLiquidity(address indexed liquidityProvider, uint256 amount); event MintCherry(address indexed liquidityProvider, uint256 amountDai,uint256 amountcDai, uint256 amountCherryDai); event RedeemCherry(address indexed liquidityProvider, uint256 redeemedCherryDaiDaiAmount); event TransferDai(address indexed to, uint256 value); event CurrentExchangeRate(uint256 rate); event PoolShare(uint256 amount); event FreeLongPool(uint256 amount); event FreeShortPool(uint256 amount); event SetCherryDai(address cherryDai); /** * @notice Initialize contract states */ function initialize(address _token, address _cToken, address _cherryMath) public initializer { owner = msg.sender; token = IERC20(_token); cToken = ICERC20(_cToken); cherryMath = CherryMath(_cherryMath); } /** * @notice Modifier to check if long pool is not fully utilized */ modifier isLongUtilized() { require(calcLongPoolUtil(longPoolReserved) < 1e18, "Cherrypool::long pool if fully utilized"); _; } /** * @notice Modifier to check if short pool is not fully utilized */ modifier isShortUtilized() { require(calcShortPoolUtil(shortPoolReserved) < 1e18, "Cherrypool::short pool is fully utilized"); _; } modifier canReserveLong(uint256 _amount) { require(longPoolReserved.add(_amount) <= longPoolBalance, "Cherrypool::long pool does not have liquidity"); _; } modifier canReserveShort(uint256 _amount) { require(shortPoolReserved.add(_amount) <= shortPoolBalance, "Cherrypool::short pool does not have liquidity"); _; } /** * @notice adds liquidity to the cherry pool to offer swaps against * @param _amount amount of deposited DAI * @return cherryDaiToMint amount of minted CherryDai */ function mint(uint256 _amount) external returns (uint256) { require(_amount > 0, "Cherrypool::amount provided must be higher"); // collect liquidity from provider require(token.transferFrom(msg.sender, address(this), _amount), "Cherrypool::deposit liquidity failed"); // deposit liqudity into compound token.approve(address(cToken), _amount); // On compound this function's parameter is defined as the amount of the // asset to be supplied, in units of the underlying asset. this is the dai amount. assert(cToken.mint(_amount) == 0); // Get the pools amount in cTokens. uint256 cTokensMinted = cToken.balanceOf(address(this)); uint256 _cherryRate; _cherryRate = exchangeRate(); // mint CherryDai to liquidity provider uint256 cherryDaiToMint = _amount.mul(1e18).div(_cherryRate); cherryDai.mint(msg.sender, cherryDaiToMint); // internal accounting to store pool balances poolBalance = poolBalance.add(_amount); poolcBalance = cTokensMinted; longPoolBalance = longPoolBalance.add(_amount.div(2)); shortPoolBalance = shortPoolBalance.add(_amount.div(2)); emit DepositLiquidity(msg.sender, _amount); emit MintCherry(msg.sender, _amount, cTokensMinted, cherryDaiToMint); return cherryDaiToMint; } /** * @notice Get long pool utilization * @param _longPoolReserved amount of liquidity reserved in the long pool * @return current long pool utilization as a decimal scaled 10*18 */ function calcLongPoolUtil(uint256 _longPoolReserved) public view returns (uint256) { return (_longPoolReserved * 1e18) / longPoolBalance; } /** * @notice Get short pool utilization * @param _shortPoolReserved amount of liquidity reserved in the short pool * @return current short pool utilization as a decimal scaled 10*18 */ function calcShortPoolUtil(uint256 _shortPoolReserved) public view returns (uint256) { return (_shortPoolReserved * 1e18) / shortPoolBalance; } /** * @notice Get Cherrydai balance for liquidity provider * @param _provider liquidity provider address * @return CherryDai balance */ function cherryDaiBalanceOf(address _provider) public view returns (uint256) { return cherryDai.balanceOf(_provider); } /** * @notice transfer underlying asset back to liquidity provider assuming pool liquidity is still sufficient. * @dev the amount returned is the number of cherrytokens multiplied by the current exchange rate * The sender should approve the _amount to this contract address * @param _amount amount of CherryDai to redeem * @return daiRedeemed amount of DAI redeemed */ function redeem(uint256 _amount) external isLongUtilized() isShortUtilized() returns (uint256) { require( _amount <= cherryDai.balanceOf(msg.sender), "CherryPool::redeem request is more than current token balance" ); // get exchange rate from Cherrydai to Dai+fee uint256 _cherryRate; _cherryRate = exchangeRate(); uint256 daiRedeemed = _amount.mul(_cherryRate).div(1e18); require(getCashPrior() < daiRedeemed, "Redeem:insufficient cash"); // pay the message.sender the daiRedeemed amount and burn their _amount of CherryDai payout(msg.sender, daiRedeemed, _amount); emit RedeemCherry(msg.sender, _amount); return daiRedeemed; } /** * @notice Get available pool balance (total pool balance - total reserved balance) * @return available pool balance */ function getCashPrior() internal returns (uint256) { return poolBalance.sub((shortPoolReserved.add(longPoolReserved))); } /** * @notice Transfer the underlying asset * @param _redeemer redeemer address * @param _redeemedDaiAmount amount of DAI to transfer * @param _redeemedCherryDaiTokens amount of CherryDAI to burn */ function payout(address _redeemer, uint256 _redeemedDaiAmount, uint256 _redeemedCherryDaiTokens) internal { // Remove the CherryDai from the supply cherryDai.burnFrom(_redeemer, _redeemedCherryDaiTokens); // redeem an amount of underlying by sending cDai to compound in exchange for Dai. require(cToken.redeemUnderlying(_redeemedDaiAmount) == 0, "CherryPool::payout - something went wrong"); // transfer Dai to redeemer. token.transfer(_redeemer, _redeemedDaiAmount); emit TransferDai(_redeemer, _redeemedDaiAmount); } /** * @notice the rate of CherryDai redeemable for Dai. * @dev Each CherryDai is convertible into the underlying asset + the fees accrued through liquidity provision. * @return rate Exchange rate */ function exchangeRate() public returns (uint256) { uint256 rate; if(cherryDai.totalSupply() == 0) { rate = 1; } else { rate = (uint256(int256(poolcBalance) + poolcTokenProfit).mul(getcTokenExchangeRate())).div(cherryDai.totalSupply()); } emit CurrentExchangeRate(uint256(rate)); return uint256(rate); } /** * @notice Set CherryDai token address * @dev can only be called by the owner * @param _token CherryDai token address */ function setToken(address _token) external { require(msg.sender == owner, "Cherrypool::not authorized to call function"); cherryDai = CherryDai(_token); emit SetCherryDai(_token); } function _reserveLongPool(uint256 _amount) internal canReserveLong(_amount) { require(_amount > 0, "Cherrypool::invalid amount to reserve"); longPoolReserved = longPoolReserved.add(_amount); } function _reserveShortPool(uint256 _amount) internal canReserveShort(_amount) { require(_amount > 0, "Cherrypool::invalid amount to reserve"); shortPoolReserved = shortPoolReserved.add(_amount); } function _freeLongPool(uint256 _amount) internal { require(_amount > 0, "Cherrypool::invalid amount to free"); longPoolReserved.sub(_amount); emit FreeLongPool(_amount); } function _freeShortPool(uint256 _amount) internal { require(_amount > 0, "Cherrypool::invalid amount to free"); shortPoolReserved.sub(_amount); emit FreeShortPool(_amount); } function _addcTokenPoolProfit(int256 _profit) internal { poolcTokenProfit += _profit; } function getcTokenExchangeRate() public view returns (uint256) { return cToken.exchangeRateStored(); } }
transfer underlying asset back to liquidity provider assuming pool liquidity is still sufficient. the amount returned is the number of cherrytokens multiplied by the current exchange rate The sender should approve the _amount to this contract address _amount amount of CherryDai to redeem return daiRedeemed amount of DAI redeemed/ get exchange rate from Cherrydai to Dai+fee pay the message.sender the daiRedeemed amount and burn their _amount of CherryDai
function redeem(uint256 _amount) external isLongUtilized() isShortUtilized() returns (uint256) { require( _amount <= cherryDai.balanceOf(msg.sender), "CherryPool::redeem request is more than current token balance" ); uint256 _cherryRate; _cherryRate = exchangeRate(); uint256 daiRedeemed = _amount.mul(_cherryRate).div(1e18); require(getCashPrior() < daiRedeemed, "Redeem:insufficient cash"); payout(msg.sender, daiRedeemed, _amount); emit RedeemCherry(msg.sender, _amount); return daiRedeemed; }
1,044,709
// SPDX-License-Identifier: MIT /** °° °° °° °°° ######### ### ####### ######. °°°° °° °° °° °° ## ## ## ## ## ## °° °° °° °° °° °° ## ## ## ####### #### °°°°°°°° °° °° °° °° ## ## #### ## ## ## ## °° °° °° °° °° °° ## ## ## ## ## . # °° °° °°° °°° ## ## ## ## ## ###### */ pragma solidity ^0.8.7; import 'erc721a/contracts/ERC721A.sol'; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; contract AVOTARS is ERC721A, Ownable, ReentrancyGuard { using Strings for uint256; bytes32 public merkleRoot; mapping(address => bool) public whitelisted; string public baseURI = "ipfs://QmQzHtuMZxLJiFdALzxXrEtypwG5q7sj4ADb8UGY4xx3zm/"; uint256 public price; uint256 public maxAmountForAddress; uint256 public maxSupply = 10; bool public paused = false; bool public revealed = false; bool public whitelistMintEnabled = false; constructor() ERC721A("AVOTAR", "AVT") {} // imposta prezzo function setPrice (uint256 _price) public onlyOwner { price = _price; } function setMaxAmounthForAddress (uint256 _maxAmountForAddress) public onlyOwner { maxAmountForAddress = _maxAmountForAddress; } // un tipo di funzione che controlla prima se la quantità data in input rispetta i limiti imposti // questa funzione verà richiamata nelle funzioni di mint modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxAmountForAddress, "Invalid mint amount!"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } // un tipo di funzione che verifica se i fonfi presenti nel wallet sono suficienti per acquistare la quantità scelta di nft // questa funzione verà richiamata nelle funzioni di mint modifier mintPriceAVOTAR(uint256 _mintAmount) { require(msg.value >= price * _mintAmount, "Insufficient funds!"); _; } // la funzione permette di mintare solo a chi è nella WL function whitelistMint(uint256 _mintAmount, bytes32[] calldata _merkleProof) public payable mintCompliance(_mintAmount) mintPriceAVOTAR(_mintAmount) { require(!paused, "The contract is paused!"); require(whitelistMintEnabled, "The whitelist sale is not enabled!"); require(!whitelisted[_msgSender()], "Address already claimed!"); bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof!"); whitelisted[_msgSender()] = true; // il mitente è nella WL _safeMint(_msgSender(), _mintAmount); // viene salvata la quantità del mint } // la funzione è riservata al mint publico function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) mintPriceAVOTAR(_mintAmount) { require(!paused, "The contract is paused!"); _safeMint(_msgSender(), _mintAmount); } //ONLY OWNER // la funzione è riservata per il mint del proprietario function Owner_mint(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _safeMint(_receiver, _mintAmount); } // imposta l'uri dei metadata nascosti function _baseURI() internal view override returns (string memory) { return baseURI; } // una volta clicato reveal gli nft vengono rivelati e non è possibile nasconderli più function reveal(bool _revealed) public onlyOwner { revealed = _revealed; } function changeBaseURI(string memory changeURI) public onlyOwner { baseURI = changeURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory changeURI = _baseURI(); if (revealed) { return bytes(changeURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } else { return string(abi.encodePacked(changeURI, ".json")); } } // imposta lo stato del contratto se è in pausa allora paused = true e viceversa function setPaused(bool _state) public onlyOwner { paused = _state; } // imposta la radice dell'albero di Markle contenente gli hash degli address di collloro che sono nella WL function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } // imposta lo stato del mint per chi è nella WL abile = true e viceversa function setWhitelistMintEnabled(bool _state) public onlyOwner { whitelistMintEnabled = _state; } // tipica funzione di ERC721A che verifica il balance del address dato in output // alla variabile ownerTokenCount viene attribuito il valore del balans del address dato in input // viene memorizzata la quantità dei token con il loro id presenti nel balanc del address dato in input function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = _startTokenId(); uint256 ownedTokenIndex = 0; address latestOwnerAddress; // mentre vengono rispettate le condizioni vengono memorizzati i correnti token id while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { TokenOwnership memory ownership = _ownerships[currentTokenId]; // se la proprieta viene bruciata e l'address del proprietario è diverso da 0 // allora il valore dell'address del proprietario che ha brucciato viene passato alla variabile dell'address più recente del proprietario if (!ownership.burned && ownership.addr != address(0)) { latestOwnerAddress = ownership.addr; } // se l'address più recente del proprietari è = all'address del proprietario // allora l'id e il suo index viene passato alla variabile currentTokenId if (latestOwnerAddress == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } // il token id parte da 1 e non da 0 function _startTokenId() internal view virtual override returns (uint256) { return 1; } }
imposta la radice dell'albero di Markle contenente gli hash degli address di collloro che sono nella WL
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; }
986,685
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ut-0/ERC20.sol"; import "./libraries/Pointer.sol"; import "./libraries/Checkpoint.sol"; contract Attest is ERC20 { using Checkpoint for Checkpoint.Data[]; using Checkpoint for mapping(address => Checkpoint.Data[]); using Pointer for Pointer.Data[]; using Pointer for mapping(address => Pointer.Data[]); error InvalidBlockNumber(uint32 blockNumber); /// @dev The delegation destination history. mapping(address => Pointer.Data[]) internal _pointerOf; /// @dev The delegation amount history. mapping(address => Checkpoint.Data[]) internal _checkpoints; constructor( string memory name_, string memory symbol_, uint8 decimals_ ) ERC20(name_, symbol_, decimals_) {} function magnitude(address account) external view returns (uint256) { return _pointerOf[account].length; } /// @dev Returns the length of pointers and checkpoints. function cardinality(address account) external view returns (uint256) { return _checkpoints[account].length; } function pointerOf(address account) external view returns (address) { return _pointerOf[account].latest(); } function pointerIn(address account, uint256 blockNumber) external view returns (address) { if (blockNumber <= block.number) return _pointerOf[account].lookup(blockNumber); else revert InvalidBlockNumber(uint32(blockNumber)); } function pointerAt( address account, uint256 index ) external view returns (address, uint32, uint32) { require(index < _pointerOf[account].length, "OutOfBounds"); Pointer.Data memory pointer = _pointerOf[account][index]; return (pointer.value, pointer.startBlock, pointer.endBlock); } function weightOf(address account) external view returns (uint256) { return _checkpoints[account].latest(); } function weightIn(address account, uint256 blockNumber) external view returns (uint256) { if (blockNumber <= block.number) return _checkpoints[account].lookup(blockNumber); else revert InvalidBlockNumber(uint32(blockNumber)); } function weightAt( address account, uint256 index ) external view returns (uint160, uint32, uint32) { require(index < _checkpoints[account].length, "OutOfBounds"); Checkpoint.Data memory checkpoint = _checkpoints[account][index]; return (checkpoint.amount, checkpoint.startBlock, checkpoint.endBlock); } function mint(address to, uint256 amount) external returns (bool) { return _mint(to, amount); } function burn(address from, uint256 amount) external returns (bool) { return _burn(from, amount); } /// @dev Delegate voting rights to another account. function delegate(address to) external { _delegate(msg.sender, to); } function _delegate(address from, address to) internal { _checkpoints.move(_pointerOf[from].latest(), to, _balanceOf[from]); _pointerOf[from].save(to); } /// @dev Called on {mint}, {burn}, {transfer} and {transferFrom}. /// @dev Should be used to update when transferring shares to a delegated account. function _after(address from, address to, uint256 amount) internal override virtual { _checkpoints.move(_pointerOf[from].latest(), _pointerOf[to].latest(), amount); } }
Returns the length of pointers and checkpoints.
function cardinality(address account) external view returns (uint256) { return _checkpoints[account].length; }
5,351,366
pragma solidity 0.5.0; import "./StringUtil.sol"; import "../contracts/MarketplaceSecurity.sol"; /** @title Marketplace. * @author Juho Lehtonen */ contract Marketplace is MarketplaceSecurity { using StringUtil for string; enum UserStatus { Shopper, StoreOwner, Admin, WaitingApproval } struct User { UserStatus status; uint storefrontCount; uint index; } mapping(address => User) private users; address[] private userIndex; struct Storefront { string name; uint balance; uint productCount; } uint private constant MAX_STOREFRONT_COUNT = 5; mapping(address => Storefront[MAX_STOREFRONT_COUNT]) private storefronts; struct Product { string name; uint price; uint quantity; bytes32 picIpfsHash; } uint private constant MAX_PRODUCT_COUNT = 10; uint private constant MAX_PRODUCT_QUANTITY = 200; mapping(address => mapping(uint => Product[MAX_PRODUCT_COUNT])) private products; event LogAdminRightsGranted(address addr); event LogStoreOwnerRightsGranted(address addr); event LogStoreOwnerRightsRequested(address addr); event LogDeleteUser(address indexed addr, uint index); event LogNewStorefrontCreated(address owner, string name, uint balance, uint productCount); event LogStorefrontRemoved(address storeOwner, uint storeIndex); event LogNewProductAdded(string name, uint price, uint quantity); event LogProductRemoved(address storeOwner, uint storeIndex, uint index); event LogPurchaseProduct(address storeOwner, uint storeIndex, uint productIndex, uint quantity); event LogWithdraw(address addr, uint storeIndex, uint amount); event LogProductPictureIpfsHashAdded(address storeOwner, uint storeIndex, uint index); modifier verifyCallerIsAdmin () { require(users[msg.sender].status == UserStatus.Admin, "Caller is not admin"); _; } modifier verifyAddressIsStoreOwnerOrAdmin(address addr) { require(users[addr].status == UserStatus.Admin || users[addr].status == UserStatus.StoreOwner, "Address is neither admin nor store owner"); _; } modifier isNotShopper (address storeOwner) { require(users[storeOwner].status != UserStatus.Shopper, "Address is shopper"); _; } modifier isNotYetStoreOwner (address newStoreOwner) { require(users[newStoreOwner].status != UserStatus.StoreOwner, "Address is already store owner"); _; } modifier isNotAdmin (address newAdmin) { require(users[newAdmin].status != UserStatus.Admin, "Address is already admin"); _; } modifier isUser (address userAddress) { require(userIndex.length > 0, "There is no users"); require(userIndex[users[userAddress].index] == userAddress, "No such user"); _; } modifier isNotUser (address userAddress) { require(userIndex[users[userAddress].index] != userAddress, "User already exisist"); _; } modifier storeIndexExists (uint storefrontCount, uint index) { require(storefrontCount > 0 || storefrontCount - 1 < index, "Storefront does not exist."); _; } modifier storefrontMaxCapacityReached (uint storefrontCount) { require(storefrontCount < MAX_STOREFRONT_COUNT, "Max storefront count reached."); _; } modifier isValidWithdrawAmount (address storeOwner, uint storeIndex, uint amount) { require(amount > 0 && storefronts[storeOwner][storeIndex].balance >= amount, "Invalid withdraw amount"); _; } modifier isValidProductPrice (uint price) { require(price > 0, "Invalid price"); _; } modifier productIndexExists (uint productCount, uint index) { require(productCount > 0 || productCount - 1 < index, "Product does not exist."); _; } modifier productMaxCapacityReached (uint productCount) { require(productCount < MAX_PRODUCT_COUNT, "Max product count reached for collection."); _; } modifier isValidPurchaseQuantity(uint purchaseQuantity) { require( purchaseQuantity > 0 && purchaseQuantity <= MAX_PRODUCT_QUANTITY, "Product purchase quantity is invalid"); _; } modifier isValidProductQuantity(uint quantity) { require(quantity > 0 && quantity <= MAX_PRODUCT_QUANTITY, "Product quantity is invalid"); _; } /** @notice Create contract. * @dev Contract creator is always admin. */ constructor() public { owner = msg.sender; users[msg.sender] = User({status: UserStatus.Admin, storefrontCount: 0, index: userIndex.length}); userIndex.push(msg.sender); emit LogAdminRightsGranted(msg.sender); } /** @notice Grant store owner rights for user. * @dev Store owner rights can be granted only by admin. Only users that has * requested store owner rights can be promoted. * @param newStoreOwner User address that will be granted with store owner right. */ function addStoreOwner(address newStoreOwner) public isContractActivated() verifyCallerIsAdmin() isUser(newStoreOwner) isNotYetStoreOwner(newStoreOwner) { externalEnter(); users[newStoreOwner].status = UserStatus.StoreOwner; emit LogStoreOwnerRightsGranted(newStoreOwner); externalLeave(); } /** @notice Grant store admin rights for user. * @dev Admin rights can be granted only by admin. Only users that has * requested store owner rights can be promoted. * @param newAdmin User address that will be granted with admin right. */ function addAdmin(address newAdmin) public isContractActivated() verifyCallerIsAdmin() isUser(newAdmin) isNotAdmin(newAdmin) { externalEnter(); users[newAdmin].status = UserStatus.Admin; emit LogAdminRightsGranted(newAdmin); externalLeave(); } /** @notice Request store owner rights for caller. * @dev Request is needed before shop owner rights can be granted. */ function requestStoreOwnerStatus() public isContractActivated() isNotYetStoreOwner(msg.sender) { externalEnter(); users[msg.sender] = User({status: UserStatus.WaitingApproval, storefrontCount: 0, index: userIndex.length}); userIndex.push(msg.sender); emit LogStoreOwnerRightsRequested(msg.sender); externalLeave(); } /** @notice Delete registered user. * @dev Last item of the users map will be moved to index that will be removed. * Index is also updated accordingly for the moved item. After that last user * address is removed from the userIndexes. */ function deleteUser(address userAddress) public isContractActivated() isUser(userAddress) { externalEnter(); uint deleteRow = users[userAddress].index; address updateKey = userIndex[userIndex.length-1]; userIndex[deleteRow] = updateKey; users[updateKey].index = deleteRow; userIndex.pop(); users[userAddress].status = UserStatus.Shopper; emit LogDeleteUser(userAddress, deleteRow); externalLeave(); } /** @notice Get User status for the given address. * @param userAddress User's address. * @return userStatus Status of the registered user. */ function getUserStatus(address userAddress) public view returns (UserStatus userStatus) { return users[userAddress].status; } /** @notice Get all registered users and their statuses. * @dev Returns two arrays. Users array index is corresponding to status array index. * @return addrs Array of users' addresses * @return statuses Array of users' statuses */ function getUsers() public view returns (address[] memory addrs, UserStatus[] memory statuses) { uint userCount = userIndex.length; statuses = new UserStatus[](userCount); addrs = new address[](userCount); for (uint i = 0; i < userCount; i++) { addrs[i] = userIndex[i]; statuses[i] = users[userIndex[i]].status; } return (addrs, statuses); } /** @notice Add new storefront. * @dev Caller needs to be store owner or admin. * @param name Name for new storefront. */ function addStorefront(string memory name) public isContractActivated() verifyAddressIsStoreOwnerOrAdmin(msg.sender) isValidString(name) storefrontMaxCapacityReached(users[msg.sender].storefrontCount) { externalEnter(); uint storefrontCount = users[msg.sender].storefrontCount; storefronts[msg.sender][storefrontCount] = Storefront( {name: name, balance: 0, productCount: 0}); users[msg.sender].storefrontCount++; emit LogNewStorefrontCreated(msg.sender, name, 0, 0); externalLeave(); } /** @notice Remove existing storefront owned by store owner. * @dev Caller needs to be store owner or admin. Store owner can remove only * own stores and admin can remove any store. * @param storeOwner Store owner's address that has storefront to be removed. * @param storeIndex Storefront index that will be removed. */ function removeStorefront(address storeOwner, uint storeIndex) public isContractActivated() verifyAddressIsStoreOwnerOrAdmin(msg.sender) { externalEnter(); // store owner can remove own stores if ( users[msg.sender].status == UserStatus.StoreOwner ) { handleStorefrontRemoval(msg.sender, storeIndex); } // admin can remove every storefront else { handleStorefrontRemoval(storeOwner, storeIndex); } emit LogStorefrontRemoved(storeOwner, storeIndex); externalLeave(); } /** @notice Add product to specified storefront. * @dev Caller needs to be store owner or admin. * @param storeIndex Storefront index that will be removed. * @param name Name of product. * @param price Price of product. * @param quantity Quantity of product. */ function addProductToStoreFront(uint storeIndex, string memory name, uint price, uint quantity) public isContractActivated() verifyAddressIsStoreOwnerOrAdmin(msg.sender) storeIndexExists(users[msg.sender].storefrontCount, storeIndex) productMaxCapacityReached(storefronts[msg.sender][storeIndex].productCount) isValidString(name) isValidProductQuantity(quantity) isValidProductPrice(price) { externalEnter(); uint productCount = storefronts[msg.sender][storeIndex].productCount; products[msg.sender][storeIndex][productCount] = Product({ name: name, price: price, quantity: quantity, picIpfsHash: "" }); storefronts[msg.sender][storeIndex].productCount++; emit LogNewProductAdded(name, price, quantity); externalLeave(); } /** @notice Remove product from specified storefront. * @dev Caller needs to be store owner or admin. Store owner can remove * only own products and admin can remove any product. * @param storeOwner Store owner address. * @param storeIndex Storefront index that contains product to be removed. * @param productIndex Product index that will be removed. */ function removeProductFromStorefront(address storeOwner, uint storeIndex, uint productIndex) public isContractActivated() verifyAddressIsStoreOwnerOrAdmin(msg.sender) { externalEnter(); // store owner can remove own product if ( users[msg.sender].status == UserStatus.StoreOwner ) { deleteProduct(msg.sender, storeIndex, productIndex); } // admin can remove any product else { deleteProduct(storeOwner, storeIndex, productIndex); } emit LogProductRemoved(storeOwner, storeIndex, productIndex); externalLeave(); } /** @notice Get all products from specified storefront. * @dev Returns three arrays: names (in bytes), prices and quantities. * Array indexes is corresponding with each other. * @param storeOwner Store owner address. * @param storeIndex Storefront index that contains products to be returned. * @return names Array of product names in bytes. * @return prices Array of product prices. * @return quantities Array of product quantities. * @return ipfsHash Array of product IPFS hash in bytes. */ function getAllProductsFromStorefront(address storeOwner, uint storeIndex) public view verifyAddressIsStoreOwnerOrAdmin(storeOwner) storeIndexExists(users[storeOwner].storefrontCount, storeIndex) returns(bytes memory names, uint[] memory prices, uint[] memory quantities, bytes32[] memory ipfsHashes) { uint pCount = storefronts[storeOwner][storeIndex].productCount; prices = new uint[](pCount); quantities = new uint[](pCount); ipfsHashes = new bytes32[](pCount); for (uint i = 0; i < pCount; i++) { Product storage product = products[storeOwner][storeIndex][i]; prices[i] = product.price; quantities[i] = product.quantity; ipfsHashes[i] = product.picIpfsHash; } names = getProductNamesInBytes(storeOwner, storeIndex); return (names, prices, quantities, ipfsHashes); } /** @notice Get all storefronts. * @dev Returns three arrays: names (in bytes), balances and * product count. Array indexes is corresponding with each other. * @param storeOwner Store owner address that owns storefronts. * @return names Array of storefront names in bytes. * @return balances Array of storefront balances. * @return productCount Array of storefront product counts */ function getStorefronts(address storeOwner) public view isNotShopper(storeOwner) returns(bytes memory names, uint[] memory balances, uint[] memory productCount) { uint storefrontCount = users[storeOwner].storefrontCount; balances = new uint[](storefrontCount); productCount = new uint[](storefrontCount); for (uint i = 0; i < storefrontCount; i++) { Storefront storage sf = storefronts[storeOwner][i]; balances[i] = sf.balance; productCount[i] = sf.productCount; } return (getStorefrontNamesInBytes(storefrontCount, storeOwner), balances, productCount); } /** @notice Purchase product. * @dev If sended value is bigger than * @param storeOwner Store owner address. * @param storeIndex Storefront index that contains product to be purchased. * @param productIndex Product index to be purchased. * @param quantity Purchase quantity. */ function purchaseProduct(address storeOwner, uint storeIndex, uint productIndex, uint quantity) public payable isContractActivated() verifyAddressIsStoreOwnerOrAdmin(storeOwner) productIndexExists(storefronts[storeOwner][storeIndex].productCount, productIndex) { externalEnter(); Product storage product = products[storeOwner][storeIndex][productIndex]; require(product.quantity >= quantity, "Product quantity is not enough"); uint priceInTotal = product.price * quantity; // check if paid enough require(msg.value >= priceInTotal, "Not enough paid"); handleProductPurchase(storeOwner, storeIndex, productIndex, quantity); storefronts[storeOwner][storeIndex].balance += priceInTotal; // refund uint refund = msg.value - priceInTotal; if (refund > 0) { msg.sender.transfer(refund); } emit LogPurchaseProduct(storeOwner, storeIndex, productIndex, quantity); externalLeave(); } /** @notice Withdraw funds that have been earned. * @dev User can only withdraw funds from own storefront. * @param storeIndex Storefront index where funds will be withdrawed. * @param amount Amount of funds that will be withdrawed from the storefront. */ function withdrawFunds(uint storeIndex, uint amount) public payable isContractActivated() isWithdrawalAllowed() verifyAddressIsStoreOwnerOrAdmin(msg.sender) storeIndexExists(users[msg.sender].storefrontCount, storeIndex) isValidWithdrawAmount(msg.sender, storeIndex, amount) { externalEnter(); storefronts[msg.sender][storeIndex].balance = storefronts[msg.sender][storeIndex].balance - amount; msg.sender.transfer(amount); emit LogWithdraw(msg.sender, storeIndex, amount); externalLeave(); } /** @notice Withdraw all funds in case of emergency. * @dev Contract should be deactivated before function call. * This function can be called only contract owner. */ function emergencyWithdraw() public payable isOwner() isContractDeactivated() { externalEnter(); // collect users' balances uint userCount = userIndex.length; uint contractBalance = 0; for (uint i = 0; i < userCount; i++) { contractBalance += getUserBalance(userIndex[i]); } // set empty balances for (uint k = 0; k < userCount; k++) { address userAddress = userIndex[k]; uint storefrontCount = users[userAddress].storefrontCount; for (uint l = 0; l < storefrontCount; l++) { storefronts[userAddress][l].balance = 0; } } // withdraw everything address payable ownerPayable = address(uint160(owner)); if (contractBalance > 0) { ownerPayable.transfer(contractBalance); } externalLeave(); } /** @notice Get combined balance of storefronts for user. * @param userAddress User's address that owns storefront. * @return combinedBalance Combined balance of storefronts for the given user. */ function getUserBalance(address userAddress) public view isUser(userAddress) returns (uint combinedBalance) { uint storefrontCount = users[userAddress].storefrontCount; uint totalBalance = 0; for (uint i = 0; i < storefrontCount; i++) { totalBalance += storefronts[userAddress][i].balance; } return totalBalance; } /** @notice Update product price. * @dev Only store owner can update own products' prices. * @param storeIndex Storefront index that contains product to be updated. * @param productIndex Product index that will be updated. * @param newPrice New price for the product. */ function updatePrice(uint storeIndex, uint productIndex, uint newPrice) public isContractActivated() verifyAddressIsStoreOwnerOrAdmin(msg.sender) storeIndexExists(users[msg.sender].storefrontCount, storeIndex) isValidProductPrice(newPrice) { externalEnter(); products[msg.sender][storeIndex][productIndex].price = newPrice; externalLeave(); } /** @notice Update IPFS hash code for the product picture. * @dev Picture hash is initialized as empty when product is created. Hash is in hex format * without "Qm" prefix so it fits to bytes32. * Picture hash needs to be added afterwards. * @param storeIndex Storefront index that contains product to be updated. * @param productIndex Product index that will be updated. * @param picIpfsHash Product picture hash in IPFS */ function updateIpfsHashForProductPic(uint storeIndex, uint productIndex, bytes32 picIpfsHash) public isContractActivated() verifyAddressIsStoreOwnerOrAdmin(msg.sender) storeIndexExists(users[msg.sender].storefrontCount, storeIndex) { externalEnter(); products[msg.sender][storeIndex][productIndex].picIpfsHash = picIpfsHash; emit LogProductPictureIpfsHashAdded(msg.sender, storeIndex, productIndex); externalLeave(); } /** @notice Get storefront names in bytes. * @dev Iterate through strorefronts and transfer names into bytes. * @return serialized Names array in bytes. */ function getStorefrontNamesInBytes(uint storefrontCount, address storeOwner) private view returns(bytes memory serialized) { uint offset = 64*storefrontCount; bytes memory buffer = new bytes(offset); string memory str = new string(32); for (uint i = storefrontCount - 1; i < storefrontCount; i--) { str = storefronts[storeOwner][i].name; StringUtil.stringToBytes(offset, bytes(str), buffer); offset -= str.getSize(); } return (buffer); } /** @notice Delete product from the collection. * @param productIndex Product index that will be removed. */ function deleteProduct(address storeOwner, uint storeIndex, uint productIndex) private storeIndexExists(users[storeOwner].storefrontCount, storeIndex) productIndexExists(storefronts[storeOwner][storeIndex].productCount, productIndex) { uint lastIndexBeforeRemoval = storefronts[storeOwner][storeIndex].productCount - 1; Product memory lastProduct = products[storeOwner][storeIndex][lastIndexBeforeRemoval]; if (lastIndexBeforeRemoval > 0) { products[storeOwner][storeIndex][productIndex] = lastProduct; } storefronts[storeOwner][storeIndex].productCount--; } /** @notice Handle product purchase book keeping. * @param index Product index to be purchased. * @param purchaseQuantity Purchase quantity. */ function handleProductPurchase(address storeOwner, uint storeIndex, uint index, uint purchaseQuantity) private productIndexExists(storefronts[storeOwner][storeIndex].productCount, index) { Product storage product = products[storeOwner][storeIndex][index]; uint existingQuantity = product.quantity; if (existingQuantity - purchaseQuantity == 0) { deleteProduct(storeOwner, storeIndex, index); } else { products[storeOwner][storeIndex][index].quantity = existingQuantity - purchaseQuantity; } } /** @notice Get product names in bytes. * @dev Iterate through products and transfer names into bytes. * @return serialized Names array in bytes. */ function getProductNamesInBytes(address storeOwner, uint storeIndex) private view returns(bytes memory serialized) { uint pCount = storefronts[storeOwner][storeIndex].productCount; uint offset = 64*pCount; bytes memory buffer = new bytes(offset); string memory str = new string(32); for (uint i = pCount - 1; i < pCount; i--) { str = products[storeOwner][storeIndex][i].name; StringUtil.stringToBytes(offset, bytes(str), buffer); offset -= str.getSize(); } return (buffer); } /** @notice Remove existing storefront. * @param storeIndex Storefront index that will be removed. */ function handleStorefrontRemoval(address storeOwner, uint storeIndex) private storeIndexExists(users[storeOwner].storefrontCount, storeIndex) { uint lastIndexBeforeRemoval = users[storeOwner].storefrontCount - 1; Storefront memory lastStore = storefronts[storeOwner][lastIndexBeforeRemoval]; storefronts[storeOwner][storeIndex] = lastStore; users[storeOwner].storefrontCount--; } }
Delete registered user. Last item of the users map will be moved to index that will be removed. Index is also updated accordingly for the moved item. After that last user address is removed from the userIndexes./
function deleteUser(address userAddress) public isContractActivated() isUser(userAddress) { externalEnter(); uint deleteRow = users[userAddress].index; address updateKey = userIndex[userIndex.length-1]; userIndex[deleteRow] = updateKey; users[updateKey].index = deleteRow; userIndex.pop(); users[userAddress].status = UserStatus.Shopper; emit LogDeleteUser(userAddress, deleteRow); externalLeave(); }
2,535,687
/** *Submitted for verification at Etherscan.io on 2020-11-18 */ /** *Submitted for verification at Etherscan.io on 2020-07-21 */ pragma solidity ^0.6.0; interface DMEX { function availableBalanceOf(address token, address user) external view returns (uint256); function withdraw(address token, uint256 amount) external returns (bool success); } interface UniswapV2ExchangeInterface { function WETH() external pure returns (address); function swapExactTokensForTokens(uint amountIn, uint amountOutMin, 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 swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); } /* Interface for ERC20 Tokens */ interface DMEXTokenInterface { function burn(uint256 _value) external returns (bool success); } // The DMEX Fee Contract contract DMEX_Fee_Contract { address DMEX_CONTRACT = address(0x2101e480e22C953b37b9D0FE6551C1354Fe705E6); address DMEX_TOKEN = address(0x6263e260fF6597180c9538c69aF8284EDeaCEC80); address TOKEN_ETH = address(0x0000000000000000000000000000000000000000); address TOKEN_DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address TOKEN_BTC = address(0x5228a22e72ccC52d415EcFd199F99D0665E7733b); address uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address payable FEE_ACCOUNT; address owner; uint256 fee_account_share = 618e15; uint256 uniswap_share = 382e15; event Log(uint8 indexed errorId, uint value); function extractFees() public { uint256 fee_share; uint256 us_share; // extract eth uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this)); emit Log(1, eth_balance); require(DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance), "Error: failed to withdraw"); // fee_share = safeMul(eth_balance, fee_account_share) / 1e18; // us_share = safeSub(eth_balance, fee_share); // emit Log(2, fee_share); // emit Log(3, us_share); // require(FEE_ACCOUNT.send(fee_share), "Error: eth send failed"); // // swap eth for DMEX Token // address[] memory path = new address[](2); // path[0] = UniswapV2ExchangeInterface(uniswapRouter).WETH(); // path[1] = DMEX_TOKEN; // uint[] memory amounts = UniswapV2ExchangeInterface(uniswapRouter).swapExactETHForTokens.value(us_share)(1, path, address(this), 2**256 - 1); // uint token_bought = amounts[1]; // DMEXTokenInterface(DMEX_TOKEN).burn(token_bought); } constructor( address payable initialFeeAccount ) public { owner = msg.sender; FEE_ACCOUNT = initialFeeAccount; } /** Safe Math **/ // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } }
extract eth fee_share = safeMul(eth_balance, fee_account_share) / 1e18; us_share = safeSub(eth_balance, fee_share); emit Log(2, fee_share); emit Log(3, us_share); require(FEE_ACCOUNT.send(fee_share), "Error: eth send failed"); swap eth for DMEX Token address[] memory path = new address[](2); path[0] = UniswapV2ExchangeInterface(uniswapRouter).WETH(); path[1] = DMEX_TOKEN; uint[] memory amounts = UniswapV2ExchangeInterface(uniswapRouter).swapExactETHForTokens.value(us_share)(1, path, address(this), 2256 - 1); uint token_bought = amounts[1]; DMEXTokenInterface(DMEX_TOKEN).burn(token_bought);
function extractFees() public { uint256 fee_share; uint256 us_share; uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this)); emit Log(1, eth_balance); require(DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance), "Error: failed to withdraw"); } constructor( address payable initialFeeAccount
10,815,585
./full_match/1/0x37310301a4f013EF3dcef2045de2CB090cAeDf31/sources/FF_Timelock.sol
0xa2fC77A48D02dD83D17eb9DAA888aE85565B9ba1
function initialize(uint256 _initialUnlock, address _beneficiary) public onlyOwner {
3,175,181
./partial_match/1/0x8f935691e634424C8EB05EEE249bBf587ad13F4D/sources/HPOS05i.sol
generate the uniswap pair path of token -> weth make the swap
function swapTokensForHPOS10i(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = HPOS10i; _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, path, devWallet, block.timestamp ); }
4,045,627
pragma solidity 0.5.1; /** * @title Registry * @author Rob Hitchens * @notice Trustless upgradable contract implementation registry. */ import "./HitchensUnorderedAddressSet.sol"; import "./Upgradable.sol"; import "./Ownable.sol"; interface RegistryInterface { function componentUid() external view returns(bytes32); function addImplementation(address implementationAddress) external; function recallImplementation(address implementationAddress) external; function setDefaultImplementation(address implementationAddress) external; function setMyImplementation(address implementationAddress) external; function userImplementation(address user) external view returns(address); function myImplementation() external view returns(address); function isImplementation(address implementationAddress) external view returns(bool); function implementationCount() external view returns(uint); function implementationAtIndex(uint index) external view returns(address); } contract Registry is RegistryInterface, Ownable { using HitchensUnorderedAddressSetLib for HitchensUnorderedAddressSetLib.Set; HitchensUnorderedAddressSetLib.Set validImplementations; address defaultImplementation; address constant UNDEFINED = address(0); bytes32 COMPONENT_UID; mapping(address => address) userImplementationChoices; event LogNewRegistry(address sender, address registry); event LogNewImplementation(address sender, address implementation); event LogRecalledImplementation(address sender, address implementation); event LogNewDefaultImplementation(address sender, address implementation); event LogUserImplementation(address sender, address implementation); /** * Ensures a unique identifier for the component this registry is concerned with. */ constructor() public { COMPONENT_UID = keccak256(abi.encodePacked(msg.sender)); emit LogNewRegistry(msg.sender, address(this)); } /** * @return bytes32 The componentUid this registry accepts. */ function componentUid() public view returns(bytes32) { return COMPONENT_UID; } /** * @param implementationAddress Address of a compatible implementation contract. * @notice The componentUid() function in the implementationAddress must return a matching componentUid. This helps prevent deployment errors. */ function addImplementation(address implementationAddress) public onlyOwner { UpgradableInterface u = UpgradableInterface(implementationAddress); require(u.componentUid() == COMPONENT_UID, "Implementation.componentUid doesn't match this registry's componentUid."); validImplementations.insert(implementationAddress); emit LogNewImplementation(msg.sender, implementationAddress); } /** * @param implementationAddress The address of an implementation contract to recall. * @notice onlyOwner. Cannot recall the default implementation. */ function recallImplementation(address implementationAddress) public onlyOwner { require(implementationAddress != defaultImplementation, "Cannot recall default implementation."); validImplementations.remove(implementationAddress); emit LogRecalledImplementation(msg.sender, implementationAddress); } /** * @param implementationAddress Set the default implementation. * @notice onlyOwner. The default implementation address must be registered. */ function setDefaultImplementation(address implementationAddress) public onlyOwner { require(isImplementation(implementationAddress), "implementationAddress is not registered."); defaultImplementation = implementationAddress; emit LogNewDefaultImplementation(msg.sender, implementationAddress); } /** * @param implementationAddress User's preferred implementation. * @notice Overrides the default implementation unless the user's preferred implementation was recalled. * @notice Set to 0x0 to use the present and future default implementation set by the registry owner. */ function setMyImplementation(address implementationAddress) public { if(implementationAddress != UNDEFINED) require(isImplementation(implementationAddress), "implementationAddress is not registered."); userImplementationChoices[msg.sender] = implementationAddress; emit LogUserImplementation(msg.sender, implementationAddress); } /** * @param user The user to inspect. * @return address The user's preferred implementation address. Default if none or if the user's preferred implementation was recalled. */ function userImplementation(address user) public view returns(address) { address implementation = userImplementationChoices[user]; if(!validImplementations.exists(implementation)) return defaultImplementation; return implementation; } /** * @return address msg.sender's preferred implementation address. */ function myImplementation() public view returns(address) { return userImplementation(msg.sender); } /** * @param implementationAddress The address to check. * @return bool True if the implementation is a registered implementation. */ function isImplementation(address implementationAddress) public view returns(bool) { return validImplementations.exists(implementationAddress); } /** * @return uint The count of implementation contracts registered. */ function implementationCount() public view returns(uint) { return validImplementations.count(); } /** * @param index The row number to inspect. * @return address The address of an implementtion address. */ function implementationAtIndex(uint index) public view returns(address) { return validImplementations.keyAtIndex(index); } }
user The user to inspect. return address The user's preferred implementation address. Default if none or if the user's preferred implementation was recalled./
function userImplementation(address user) public view returns(address) { address implementation = userImplementationChoices[user]; if(!validImplementations.exists(implementation)) return defaultImplementation; return implementation; }
12,768,333
./full_match/1/0x9e2b1cb2a7c8C11ce4C2f9d86b7A34A2beC75632/sources/deploy/Contract.sol
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 worse( 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"); newspaper[owner][spender] = amount; emit Approval(owner, spender, amount); }
16,454,349
./partial_match/42/0x3AE4Fd9b9fD337152cC8AA2452869591ab565981/sources/CommunityStakeVault.sol
withdraw and delegating candidate (only for phase 1)
function delegatedWithdraw(uint _shares, address candidate) external onlyCandidate(candidate) phaseRequired(1) { _withdraw(_shares, candidate); }
3,398,104
// SPDX-License-Identifier: UNLICENCED // Implementation Copyright 2021, the author; All rights reserved // // This contract is an on-chain implementation of a concept created and // developed by John F Simon Jr in partnership with e•a•t•works and // @fingerprintsDAO pragma solidity 0.8.10; import "./EveryIconLib.sol"; import "base64-sol/base64.sol"; import "@divergencetech/ethier/contracts/erc721/ERC721CommonEnumerable.sol"; import "@divergencetech/ethier/contracts/sales/LinearDutchAuction.sol"; import "@divergencetech/ethier/contracts/utils/DynamicBuffer.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @title Every Icon /// @author @divergenceharri (@divergence_art) contract EveryIcon is ERC721CommonEnumerable, LinearDutchAuction { using DynamicBuffer for bytes; using EveryIconLib for EveryIconLib.Repository; using Strings for uint256; /// @notice Contracts containing base icons from which designs are built. EveryIconLib.Repository private repo; constructor( string memory name, string memory symbol, EveryIconLib.Repository memory repo_, address[] memory payees, uint256[] memory shares ) ERC721CommonEnumerable(name, symbol) LinearDutchAuction( LinearDutchAuction.DutchAuctionConfig({ startPoint: 0, // disabled upon deployment startPrice: 5.12 ether, unit: AuctionIntervalUnit.Time, decreaseInterval: 300, // 5 minutes decreaseSize: 0.128 ether, numDecreases: 36 }), 0.512 ether, Seller.SellerConfig({ totalInventory: 512, maxPerAddress: 0, // unlimited maxPerTx: 1, freeQuota: 42, reserveFreeQuota: true, lockTotalInventory: true, lockFreeQuota: true }), payable(0) ) { setRepository(repo_); setBeneficiary(payable(new PaymentSplitter(payees, shares))); } /**** TOKEN AND SALES CONTROLS ****/ /// @dev The current cost of a single mint can be fetched with cost(1). function buy() external payable { Seller._purchase(msg.sender, 1); } /// @dev Flag to signal permanent locking of the icon repository. bool public repositoryLocked; /// @dev Require that icon repository isn't locked yet. modifier repositoryUnlocked() { require(!repositoryLocked, "Repository locked"); _; } /// @dev Sets addresses of icon-repository contracts. function setRepository(EveryIconLib.Repository memory repo_) public onlyOwner repositoryUnlocked { repo = repo_; } /// @dev Permanently locks the icon repository addresses. function lockRepository() external onlyOwner repositoryUnlocked { repositoryLocked = true; } /// @dev Base URI for returning iframe address in tokenURI(). string public animationURIBase; /// @dev Sets current animationURIBase. function setAnimationURIBase(string memory base) external onlyOwner { animationURIBase = base; } /// @notice Hash of transaction in which front-end code is archived for /// on-chain provenance. bytes32 public codeStorageTxHash; /// @dev Sets codeStorageTxHash for front-code archival. function setCodeStorageTxHash(bytes32 txHash) external onlyOwner { codeStorageTxHash = txHash; } /// @notice Returns metadata as a JSON-encoded data URI. function tokenURI(uint256 tokenId) public view override returns (string memory) { bytes memory buf = DynamicBuffer.allocate(2**16); bytes memory tokenIdStr = bytes(tokenId.toString()); buf.appendSafe("{"); buf.appendSafe('"name":"Every Icon #'); buf.appendSafe(tokenIdStr); buf.appendSafe('","image":"data:image/svg+xml,'); buf.appendSafe(renderSVG(tokenId, 0)); buf.appendSafe('","animation_url":"'); buf.appendSafe(bytes(animationURIBase)); buf.appendSafe(tokenIdStr); buf.appendSafe('"}'); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(buf) ) ); } /// @dev Required override for LinearDutchAuction's underlying Seller; /// effectively the minting function. function _handlePurchase( address to, uint256 num, bool ) internal override { for (uint256 i = 0; i < num; i++) { _safeMint(to, totalSupply()); EveryIconLib.Token memory token; token.combMethod = INVALID_COMB_METHOD; tokens.push(token); mintingBlocks.push( uint32(block.number & EveryIconLib.MINTING_BLOCK_MASK) ); } } /**** EVERY ICON-SPECIFIC FUNCTIONS ****/ /// @notice Metadata describing every token's icon. The block in which a /// token is minted is also encoded in the image. EveryIconLib.Token[] public tokens; uint32[] public mintingBlocks; /// @notice Used to identify an unset EveryIconLib.Token. All new instances /// have this value. uint8 private constant INVALID_COMB_METHOD = 255; /// @notice Checks whether a token has already had its icon set by the owner function iconIsSet(uint256 tokenId) public view returns (bool) { return tokens[tokenId].combMethod != INVALID_COMB_METHOD; } /// @notice Time from which the front-end "ticks" icons. If an icon design /// isn't set by a collector within the allowed window, a random token is /// used and defaultSettingTime replaces iconSettingTimes. mapping(uint256 => uint256) public iconSettingTimes; uint256 defaultSettingTime; /// @notice Closes the window for token owners to set their own icons. After /// this point, unset tokens will be randomly allocated icons. function closeIconSettingWindow() public onlyOwner { defaultSettingTime = block.timestamp; } /// @notice Sets the 'starting icon'. This is only available if it has not /// already been set (either by the owner, or automatically by the contract /// when the setting window closed). function setIcon(uint256 tokenId, EveryIconLib.Token memory token) public whenNotPaused onlyApprovedOrOwner(tokenId) { require(!iconIsSet(tokenId), "Icon already set"); require(defaultSettingTime == 0, "Icon randomly set"); require(token.designIcon0 < 100, "Design icon 0 invalid"); require(token.designIcon1 < 100, "Design icon 1 invalid"); require(token.designIcon0 != token.designIcon1, "Repeated design icon"); require(token.randIcon < 28, "Random icon invalid"); require(token.combMethod < 3, "Combination method invalid"); tokens[tokenId] = token; iconSettingTimes[tokenId] = block.timestamp; } /// @notice Default icon to show in thumbnails before a design is set. The /// actual icon has first and last words set to 0. uint256[2] private defaultIcon = [ 18609191942226762260243923200536250640, 1923275577535336623121870409490058871001437930765964941608582343745444249600 ]; /// @notice Returns data required to render an icon in the browser. /// @return icon Bit-wise representation of the token. /// @return iconSettingTime The time from which the icon ticks, if non-zero. /// Zero value indicates the token is a placeholder function iconData(uint256 tokenId, uint256 ticks) public view returns (uint256[4] memory icon, uint256 iconSettingTime) { if (!iconIsSet(tokenId) && defaultSettingTime == 0) { icon[1] = defaultIcon[0]; icon[2] = defaultIcon[1]; return (icon, iconSettingTime); } EveryIconLib.Token memory token; if (iconIsSet(tokenId) == true) { token = tokens[tokenId]; iconSettingTime = iconSettingTimes[tokenId]; } else { token = EveryIconLib.randomToken(tokenId, mintingBlocks[tokenId]); iconSettingTime = defaultSettingTime; } icon = repo.startingBits(token, mintingBlocks[tokenId], ticks); return (icon, iconSettingTime); } /// @notice Ticks per second, as used by peekSVG. uint8 constant TICKS_PER_SECOND = 100; /// @notice Returns an SVG of the icon as it would be at the moment the function /// was called, having 'ticked' ever since being set at the rate TICKS_PER_SECOND function peekSVG(uint256 tokenId) external view returns (bytes memory) { uint256 startTime = iconIsSet(tokenId) ? iconSettingTimes[tokenId] : defaultSettingTime; return renderSVG( tokenId, (block.timestamp - startTime) * TICKS_PER_SECOND ); } /// @notice Returns static SVG for a particular token. This is used for thumbnails /// and in the OpenSea listing, before the viewer clicks into the animated version of /// a piece function renderSVG(uint256 tokenId, uint256 ticks) public view returns (bytes memory) { (uint256[4] memory icon, ) = iconData(tokenId, ticks); return EveryIconLib.renderSVG(icon); } } // SPDX-License-Identifier: UNLICENCED // Copyright 2021; All rights reserved // Author: @divergenceharri (@divergence_art) pragma solidity >=0.8.9 <0.9.0; /// @title Every Icon Contract (Repository Interface) /// @notice A common interface for the 4 Every Icon repositories. interface IEveryIconRepository { function icon(uint256) external view returns (uint256[4] memory); } // SPDX-License-Identifier: UNLICENCED // Implementation Copyright 2021, the author; All rights reserved // // This contract is an on-chain implementation of a concept created and // developed by John F Simon Jr in partnership with e•a•t•works and // @fingerprintsDAO pragma solidity 0.8.10; import "./IEveryIconRepository.sol"; import "@divergencetech/ethier/contracts/random/PRNG.sol"; import "@divergencetech/ethier/contracts/utils/DynamicBuffer.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @title Every Icon library /// @author @divergenceharri (@divergence_art) library EveryIconLib { using DynamicBuffer for bytes; using PRNG for PRNG.Source; using Strings for uint256; /// @dev A set of contracts containing base icons from which designs are /// built. Each MUST hold exactly 32 icons, with the first 104 being /// "design" icons and the next 28 being the "random" ones. struct Repository { IEveryIconRepository[4] icons; } /// @notice Returns the i'th "design" icon from the Repository. function designIcon(Repository storage repo, uint256 i) internal view returns (uint256[4] memory) { require(i < 100, "Invalid design icon"); return repo.icons[i / 32].icon(i % 32); } /// @notice Returns the i'th "random" icon from the Repository. function randomIcon(Repository storage repo, uint256 i) internal view returns (uint256[4] memory) { require(i < 28, "Invalid random icon"); return repo.icons[3].icon(i + 4); } /// @dev Masks the block in which an icon was minted to encode it in the /// bottom row of the image. uint256 internal constant MINTING_BLOCK_MASK = 2**32 - 1; /// @notice Constructs icon from parameters, returning a buffer of 1024 bits function startingBits( Repository storage repo, Token memory token, uint256 mintingBlock, uint256 ticks ) internal view returns (uint256[4] memory) { uint256[4] memory di0 = designIcon(repo, token.designIcon0); uint256[4] memory di1 = designIcon(repo, token.designIcon1); uint256[4] memory ri = randomIcon(repo, token.randIcon); uint256[4] memory icon; // Start by combining inputs to get the base token // // The original JavaScript piece, which this contract mimics, inverts // bits for the 'ticking' of the icons. It's easier to correct for this // by inverting all of the incoming values and performing inverted // bitwise operations here, hence the ~((~x & ~y) | ~z) patterns. if (token.combMethod == 0) { for (uint256 i = 0; i < 4; i++) { icon[i] = ~((~di0[i] & ~di1[i]) | ~ri[i]); } } else if (token.combMethod == 1) { for (uint256 i = 0; i < 4; i++) { icon[i] = ~((~di0[i] & ~di1[i]) ^ ~ri[i]); } } else if (token.combMethod == 2) { for (uint256 i = 0; i < 4; i++) { icon[i] = ~((~di0[i] | ~di1[i]) ^ ~ri[i]); } } else { // Although this won't be exposed to collectors, it allows for // testing of individual base icons via a different, inheriting // contract. for (uint256 i = 0; i < 4; i++) { icon[i] = di0[i]; } } // After combining icons, we clear the last row of the image and replace // it with a big-endian representation of the block number in which the // token was minted. We chose big-endian representation (in contrast to // 'ticks') to remain consistent with Solidity's handling of integers mintingBlock = mintingBlock & MINTING_BLOCK_MASK; icon[3] = (icon[3] & (~MINTING_BLOCK_MASK)) | mintingBlock; // Finally, we add 'ticks'. For a starting icon this will be equal to // zero, but the 'peekSVG' function is designed to see how far the icon // would have got based on the assumed iteration rate of 100 ticks per // second. // // This step is complicated by the fact that the icon animation is // effectively little-endian. We therefore need to increment from the // highest bit down. unchecked { // Although all values only ever contain a single bit, they're // defined as uint256 instead of bool to shift without the need for // casting. uint256 a; uint256 b; uint256 sum; // a+b uint256 carry; uint256 mask; // Breaking the loop based on a lack of further carry (instead of // only looping over each word once) allows for overflow should the // icon reach the end. This will never happen (see [1] for an // interesting explanation!), but conceptually it is a core part of // the artwork – otherwise it would be impossible for "every" icon // to be generated! // // [1] Schneider B. Applied Cryptography: Protocols, Algorithms, and // Source Code in C; pp. 157–8. for (uint256 i = 0; ticks + carry > 0; i = (i + 1) % 4) { mask = 1 << 255; for (uint256 j = 0; j < 256 && ticks + carry > 0; j++) { a = ticks & 1; b = (icon[i] >> (255 - j)) & 1; sum = a ^ b ^ carry; icon[i] = (icon[i] & ~mask) | (sum << (255 - j)); carry = a + b + carry >= 2 ? 1 : 0; ticks >>= 1; mask >>= 1; } } } return icon; } /// @notice Metadata defining a token's icon. struct Token { uint8 designIcon0; uint8 designIcon1; uint8 randIcon; uint8 combMethod; } /// @notice Returns a static SVG from a 1024-bit buffer. This is used for thumbnails /// and in the OpenSea listing, before the viewer clicks into the animated version of /// a piece. function renderSVG(uint256[4] memory icon) internal pure returns (bytes memory) { bytes memory svg = DynamicBuffer.allocate(2**16); // 64KB svg.appendSafe( abi.encodePacked( "<svg width='512' height='512' xmlns='http://www.w3.org/2000/svg'>", "<style>", "rect{width:16px;height:16px;stroke-width:1px;stroke:#c4c4c4}", ".b{fill:#000}", ".w{fill:#fff}", "</style>" ) ); uint256 x; uint256 y; bool bit; for (uint256 i = 0; i < 1024; i++) { x = (i % 32) * 16; y = (i / 32) * 16; bit = (icon[i / 256] >> (255 - (i % 256))) & 1 == 1; svg.appendSafe( abi.encodePacked( "<rect x='", x.toString(), "' y='", y.toString(), "' class='", bit ? "b" : "w", "'/>" ) ); } svg.appendSafe("</svg>"); return svg; } /// @notice Returns a random Token for an NFT which has not had its icon set /// by the cut-off point. Deterministically seeded from tokenId and /// mintingBlock. function randomToken(uint256 tokenId, uint256 mintingBlock) public pure returns (Token memory) { PRNG.Source src = PRNG.newSource( keccak256(abi.encodePacked(tokenId, mintingBlock)) ); return EveryIconLib.Token({ designIcon0: uint8(src.readLessThan(100)), designIcon1: uint8(src.readLessThan(100)), randIcon: uint8(src.readLessThan(28)), combMethod: uint8(src.readLessThan(3)) }); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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: 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 (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/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/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.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); } } } } // 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/extensions/ERC721Pausable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // 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), "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 // 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/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.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); } /** * @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.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // 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, "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.0 (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: MIT // OpenZeppelin Contracts v4.4.0 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @notice A Pausable contract that can only be toggled by the Owner. contract OwnerPausable is Ownable, Pausable { /// @notice Pauses the contract. function pause() public onlyOwner { Pausable._pause(); } /// @notice Unpauses the contract. function unpause() public onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; /** @notice Provides monotonic increasing and decreasing values, similar to OpenZeppelin's Counter but (a) limited in direction, and (b) allowing for steps > 1. */ library Monotonic { /** @notice Holds a value that can only increase. @dev The internal value MUST NOT be accessed directly. Instead use current() and add(). */ struct Increaser { uint256 value; } /// @notice Returns the current value of the Increaser. function current(Increaser storage incr) internal view returns (uint256) { return incr.value; } /// @notice Adds x to the Increaser's value. function add(Increaser storage incr, uint256 x) internal { incr.value += x; } /** @notice Holds a value that can only decrease. @dev The internal value MUST NOT be accessed directly. Instead use current() and subtract(). */ struct Decreaser { uint256 value; } /// @notice Returns the current value of the Decreaser. function current(Decreaser storage decr) internal view returns (uint256) { return decr.value; } /// @notice Subtracts x from the Decreaser's value. function subtract(Decreaser storage decr, uint256 x) internal { decr.value -= x; } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0; /// @title DynamicBuffer /// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also /// https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer /// @notice This library is used to allocate a big amount of container memory // which will be subsequently filled without needing to reallocate /// memory. /// @dev First, allocate memory. /// Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if /// bounds checking is required. library DynamicBuffer { /// @notice Allocates container space for the DynamicBuffer /// @param capacity The intended max amount of bytes in the buffer /// @return buffer The memory location of the buffer /// @dev Allocates `capacity + 0x60` bytes of space /// The buffer array starts at the first container data position, /// (i.e. `buffer = container + 0x20`) function allocate(uint256 capacity) internal pure returns (bytes memory buffer) { assembly { // Get next-free memory address let container := mload(0x40) // Allocate memory by setting a new next-free address { // Add 2 x 32 bytes in size for the two length fields // Add 32 bytes safety space for 32B chunked copy let size := add(capacity, 0x60) let newNextFree := add(container, size) mstore(0x40, newNextFree) } // Set the correct container length { let length := add(capacity, 0x40) mstore(container, length) } // The buffer starts at idx 1 in the container (0 is length) buffer := add(container, 0x20) // Init content with length 0 mstore(buffer, 0) } return buffer; } /// @notice Appends data to buffer, and update buffer length /// @param buffer the buffer to append the data to /// @param data the data to append /// @dev Does not perform out-of-bound checks (container capacity) /// for efficiency. function appendUnchecked(bytes memory buffer, bytes memory data) internal pure { assembly { let length := mload(data) for { data := add(data, 0x20) let dataEnd := add(data, length) let copyTo := add(buffer, add(mload(buffer), 0x20)) } lt(data, dataEnd) { data := add(data, 0x20) copyTo := add(copyTo, 0x20) } { // Copy 32B chunks from data to buffer. // This may read over data array boundaries and copy invalid // bytes, which doesn't matter in the end since we will // later set the correct buffer length, and have allocated an // additional word to avoid buffer overflow. mstore(copyTo, mload(data)) } // Update buffer length mstore(buffer, add(mload(buffer), length)) } } /// @notice Appends data to buffer, and update buffer length /// @param buffer the buffer to append the data to /// @param data the data to append /// @dev Performs out-of-bound checks and calls `appendUnchecked`. function appendSafe(bytes memory buffer, bytes memory data) internal pure { uint256 capacity; uint256 length; assembly { capacity := sub(mload(sub(buffer, 0x20)), 0x40) length := mload(buffer) } require( length + data.length <= capacity, "DynamicBuffer: Appending out of bounds." ); appendUnchecked(buffer, data); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "../utils/Monotonic.sol"; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** @notice An abstract contract providing the _purchase() function to: - Enforce per-wallet / per-transaction limits - Calculate required cost, forwarding to a beneficiary, and refunding extra */ abstract contract Seller is OwnerPausable, ReentrancyGuard { using Address for address payable; using Monotonic for Monotonic.Increaser; using Strings for uint256; /** @dev Note that the address limits are vulnerable to wallet farming. @param maxPerAddress Unlimited if zero. @param maxPerTex Unlimited if zero. @param freeQuota Maximum number that can be purchased free of charge by the contract owner. @param reserveFreeQuota Whether to excplitly reserve the freeQuota amount and not let it be eroded by regular purchases. @param lockFreeQuota If true, calls to setSellerConfig() will ignore changes to freeQuota. Can be locked after initial setting, but not unlocked. This allows a contract owner to commit to a maximum number of reserved items. @param lockTotalInventory Similar to lockFreeQuota but applied to totalInventory. */ struct SellerConfig { uint256 totalInventory; uint256 maxPerAddress; uint256 maxPerTx; uint248 freeQuota; bool reserveFreeQuota; bool lockFreeQuota; bool lockTotalInventory; } constructor(SellerConfig memory config, address payable _beneficiary) { setSellerConfig(config); setBeneficiary(_beneficiary); } /// @notice Configuration of purchase limits. SellerConfig public sellerConfig; /// @notice Sets the seller config. function setSellerConfig(SellerConfig memory config) public onlyOwner { require( config.totalInventory >= config.freeQuota, "Seller: excessive free quota" ); require( config.totalInventory >= _totalSold.current(), "Seller: inventory < already sold" ); require( config.freeQuota >= purchasedFreeOfCharge.current(), "Seller: free quota < already used" ); // Overriding the in-memory fields before copying the whole struct, as // against writing individual fields, gives a greater guarantee of // correctness as the code is simpler to read. if (sellerConfig.lockTotalInventory) { config.lockTotalInventory = true; config.totalInventory = sellerConfig.totalInventory; } if (sellerConfig.lockFreeQuota) { config.lockFreeQuota = true; config.freeQuota = sellerConfig.freeQuota; } sellerConfig = config; } /// @notice Recipient of revenues. address payable public beneficiary; /// @notice Sets the recipient of revenues. function setBeneficiary(address payable _beneficiary) public onlyOwner { beneficiary = _beneficiary; } /** @dev Must return the current cost of a batch of items. This may be constant or, for example, decreasing for a Dutch auction or increasing for a bonding curve. @param n The number of items being purchased. */ function cost(uint256 n) public view virtual returns (uint256); /** @dev Called by both _purchase() and purchaseFreeOfCharge() after all limits have been put in place; must perform all contract-specific sale logic, e.g. ERC721 minting. When _handlePurchase() is called, the value returned by Seller.totalSold() will be the pre-purchase amount. @param to The recipient of the item(s). @param n The number of items allowed to be purchased, which MAY be less than to the number passed to _purchase() but SHALL be greater than zero. @param freeOfCharge Indicates that the call originated from purchaseFreeOfCharge() and not _purchase(). */ function _handlePurchase( address to, uint256 n, bool freeOfCharge ) internal virtual; /** @notice Tracks total number of items sold by this contract, including those purchased free of charge by the contract owner. */ Monotonic.Increaser private _totalSold; /// @notice Returns the total number of items sold by this contract. function totalSold() public view returns (uint256) { return _totalSold.current(); } /** @notice Tracks the number of items already bought by an address, regardless of transferring out (in the case of ERC721). @dev This isn't public as it may be skewed due to differences in msg.sender and tx.origin, which it treats in the same way such that sum(_bought)>=totalSold(). */ mapping(address => uint256) private _bought; /** @notice Returns min(n, max(extra items addr can purchase)) and reverts if 0. @param zeroMsg The message with which to revert on 0 extra. */ function _capExtra( uint256 n, address addr, string memory zeroMsg ) internal view returns (uint256) { uint256 extra = sellerConfig.maxPerAddress - _bought[addr]; if (extra == 0) { revert(string(abi.encodePacked("Seller: ", zeroMsg))); } return Math.min(n, extra); } /// @notice Emitted when a buyer is refunded. event Refund(address indexed buyer, uint256 amount); /// @notice Emitted on all purchases of non-zero amount. event Revenue( address indexed beneficiary, uint256 numPurchased, uint256 amount ); /// @notice Tracks number of items purchased free of charge. Monotonic.Increaser private purchasedFreeOfCharge; /** @notice Allows the contract owner to purchase without payment, within the quota enforced by the SellerConfig. */ function purchaseFreeOfCharge(address to, uint256 n) public onlyOwner whenNotPaused { uint256 freeQuota = sellerConfig.freeQuota; n = Math.min(n, freeQuota - purchasedFreeOfCharge.current()); require(n > 0, "Seller: Free quota exceeded"); uint256 totalInventory = sellerConfig.totalInventory; n = Math.min(n, totalInventory - _totalSold.current()); require(n > 0, "Seller: Sold out"); _handlePurchase(to, n, true); _totalSold.add(n); purchasedFreeOfCharge.add(n); assert(_totalSold.current() <= totalInventory); assert(purchasedFreeOfCharge.current() <= freeQuota); } /** @notice Enforces all purchase limits (counts and costs) before calling _handlePurchase(), after which the received funds are disbursed to the beneficiary, less any required refunds. @param to The final recipient of the item(s). @param requested The number of items requested for purchase, which MAY be reduced when passed to _handlePurchase(). */ function _purchase(address to, uint256 requested) internal nonReentrant whenNotPaused { /** * ##### CHECKS */ SellerConfig memory config = sellerConfig; uint256 n = config.maxPerTx == 0 ? requested : Math.min(requested, config.maxPerTx); uint256 maxAvailable = config.reserveFreeQuota ? config.totalInventory - config.freeQuota : config.totalInventory; n = Math.min(n, maxAvailable - _totalSold.current()); require(n > 0, "Seller: Sold out"); if (config.maxPerAddress > 0) { bool alsoLimitSender = _msgSender() != to; bool alsoLimitOrigin = tx.origin != _msgSender() && tx.origin != to; n = _capExtra(n, to, "Buyer limit"); if (alsoLimitSender) { n = _capExtra(n, _msgSender(), "Sender limit"); } if (alsoLimitOrigin) { n = _capExtra(n, tx.origin, "Origin limit"); } _bought[to] += n; if (alsoLimitSender) { _bought[_msgSender()] += n; } if (alsoLimitOrigin) { _bought[tx.origin] += n; } } uint256 _cost = cost(n); if (msg.value < _cost) { revert( string( abi.encodePacked( "Seller: Costs ", (_cost / 1e9).toString(), " GWei" ) ) ); } /** * ##### EFFECTS */ _handlePurchase(to, n, false); _totalSold.add(n); assert(_totalSold.current() <= config.totalInventory); /** * ##### INTERACTIONS */ // Ideally we'd be using a PullPayment here, but the user experience is // poor when there's a variable cost or the number of items purchased // has been capped. We've addressed reentrancy with both a nonReentrant // modifier and the checks, effects, interactions pattern. if (_cost > 0) { beneficiary.sendValue(_cost); emit Revenue(beneficiary, n, _cost); } if (msg.value > _cost) { address payable reimburse = payable(_msgSender()); uint256 refund = msg.value - _cost; // Using Address.sendValue() here would mask the revertMsg upon // reentrancy, but we want to expose it to allow for more precise // testing. This otherwise uses the exact same pattern as // Address.sendValue(). (bool success, bytes memory returnData) = reimburse.call{ value: refund }(""); // Although `returnData` will have a spurious prefix, all we really // care about is that it contains the ReentrancyGuard reversion // message so we can check in the tests. require(success, string(returnData)); emit Refund(reimburse, refund); } } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "./Seller.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @notice A Seller with a linearly decreasing price. abstract contract LinearDutchAuction is Seller { /** @param unit The unit of "time" used for decreasing prices, block number or timestamp. NOTE: See the comment on AuctionIntervalUnit re use of Time as a unit. @param startPoint The block or timestamp at which the auction opens. A value of zero disables the auction. See setAuctionStartPoint(). @param startPrice The price at `startPoint`. @param decreaseInterval The number of units to wait before decreasing the price. MUST be non-zero. @param decreaseSize The amount by which price decreases after every `decreaseInterval`. @param numDecreases The maximum number of price decreases before remaining constant. The reserve price is therefore implicit and equal to startPrice-numDecrease*decreaseSize. */ struct DutchAuctionConfig { uint256 startPoint; uint256 startPrice; uint256 decreaseInterval; uint256 decreaseSize; // From https://docs.soliditylang.org/en/v0.8.10/types.html#enums "Enums // cannot have more than 256 members"; presumably they take 8 bits, so // use some of the numDecreases space instead. uint248 numDecreases; AuctionIntervalUnit unit; } /** @notice The unit of "time" along which the cost decreases. @dev If no value is provided then the zero UNSPECIFIED will trigger an error. NOTE: The Block unit is more reliable as it has an explicit progression (simply incrementing). Miners are allowed to have a time drift into the future although which predisposes to unexpected behaviour by which "future" costs are encountered. See the ConsenSys 15-second rule: https://consensys.net/blog/developers/solidity-best-practices-for-smart-contract-security/ */ enum AuctionIntervalUnit { UNSPECIFIED, Block, Time } /// @param expectedReserve See setAuctionConfig(). constructor( DutchAuctionConfig memory config, uint256 expectedReserve, Seller.SellerConfig memory sellerConfig, address payable _beneficiary ) Seller(sellerConfig, _beneficiary) { setAuctionConfig(config, expectedReserve); } /// @notice Configuration of price changes. DutchAuctionConfig public dutchAuctionConfig; /** @notice Sets the auction config. @param expectedReserve A safety check that the reserve, as calculated from the config, is as expected. */ function setAuctionConfig( DutchAuctionConfig memory config, uint256 expectedReserve ) public onlyOwner { // Underflow might occur is size/num decreases is too large. unchecked { require( config.startPrice - config.decreaseSize * config.numDecreases == expectedReserve, "LinearDutchAuction: incorrect reserve" ); } require( config.unit != AuctionIntervalUnit.UNSPECIFIED, "LinearDutchAuction: unspecified unit" ); require( config.decreaseInterval > 0, "LinearDutchAuction: zero decrease interval" ); dutchAuctionConfig = config; } /** @notice Sets the config startPoint. A startPoint of zero disables the auction. @dev The auction can be toggle on and off with this function, without the cost of having to update the entire config. */ function setAuctionStartPoint(uint256 startPoint) public onlyOwner { dutchAuctionConfig.startPoint = startPoint; } /// @notice Override of Seller.cost() with Dutch-auction logic. function cost(uint256 n) public view override returns (uint256) { DutchAuctionConfig storage cfg = dutchAuctionConfig; uint256 current; if (cfg.unit == AuctionIntervalUnit.Block) { current = block.number; } else if (cfg.unit == AuctionIntervalUnit.Time) { current = block.timestamp; } require( cfg.startPoint != 0 && current >= cfg.startPoint, "LinearDutchAuction: Not started" ); uint256 decreases = Math.min( (current - cfg.startPoint) / cfg.decreaseInterval, cfg.numDecreases ); return n * (cfg.startPrice - decreases * cfg.decreaseSize); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.9 <0.9.0; library PRNG { /** @notice A source of random numbers. @dev Pointer to a 4-word buffer of {seed, counter, entropy, remaining unread bits}. however, note that this is abstracted away by the API and SHOULD NOT be used. This layout MUST NOT be considered part of the public API and therefore not relied upon even within stable versions */ type Source is uint256; /// @notice Layout within the buffer. 0x00 is the seed. uint256 private constant COUNTER = 0x20; uint256 private constant ENTROPY = 0x40; uint256 private constant REMAIN = 0x60; /** @notice Returns a new deterministic Source, differentiated only by the seed. @dev Use of PRNG.Source does NOT provide any unpredictability as generated numbers are entirely deterministic. Either a verifiable source of randomness such as Chainlink VRF, or a commit-and-reveal protocol MUST be used if unpredictability is required. The latter is only appropriate if the contract owner can be trusted within the specified threat model. */ function newSource(bytes32 seed) internal pure returns (Source src) { assembly { src := mload(0x40) mstore(0x40, add(src, 0x80)) mstore(src, seed) } // DO NOT call _refill() on the new Source as newSource() is also used // by loadSource(), which implements its own state modifications. The // first call to read() on a fresh Source will induce a call to // _refill(). } /** @dev Hashes seed||counter, placing it in the entropy word, and resets the remaining bits to 256. Increments the counter BEFORE the refill (ie 0 is never used) as this simplifies round-tripping with store() and loadSource() because the stored counter state is the same as the one used for deriving the entropy pool. */ function _refill(Source src) private pure { assembly { let ctr := add(src, COUNTER) mstore(ctr, add(1, mload(ctr))) mstore(add(src, ENTROPY), keccak256(src, 0x40)) mstore(add(src, REMAIN), 256) } } /** @notice Returns the specified number of bits <= 256 from the Source. @dev It is safe to cast the returned value to a uint<bits>. */ function read(Source src, uint256 bits) internal pure returns (uint256 sample) { require(bits <= 256, "PRNG: max 256 bits"); uint256 remain; assembly { remain := mload(add(src, REMAIN)) } if (remain > bits) { return readWithSufficient(src, bits); } uint256 extra = bits - remain; sample = readWithSufficient(src, remain); assembly { sample := shl(extra, sample) } _refill(src); sample = sample | readWithSufficient(src, extra); } /** @notice Returns the specified number of bits, assuming that there is sufficient entropy remaining. See read() for usage. */ function readWithSufficient(Source src, uint256 bits) private pure returns (uint256 sample) { assembly { let pool := add(src, ENTROPY) let ent := mload(pool) sample := and(ent, sub(shl(bits, 1), 1)) mstore(pool, shr(bits, ent)) let rem := add(src, REMAIN) mstore(rem, sub(mload(rem), bits)) } } /// @notice Returns a random boolean. function readBool(Source src) internal pure returns (bool) { return read(src, 1) == 1; } /** @notice Returns the number of bits needed to encode n. @dev Useful for calling readLessThan() multiple times with the same upper bound. */ function bitLength(uint256 n) internal pure returns (uint16 bits) { assembly { for { let _n := n } gt(_n, 0) { _n := shr(1, _n) } { bits := add(bits, 1) } } } /** @notice Returns a uniformly random value in [0,n) with rejection sampling. @dev If the size of n is known, prefer readLessThan(Source, uint, uint16) as it skips the bit counting performed by this version; see bitLength(). */ function readLessThan(Source src, uint256 n) internal pure returns (uint256) { return readLessThan(src, n, bitLength(n)); } /** @notice Returns a uniformly random value in [0,n) with rejection sampling from the range [0,2^bits). @dev For greatest efficiency, the value of bits should be the smallest number of bits required to capture n; if this is not known, use readLessThan(Source, uint) or bitLength(). Although rejections are reduced by using twice the number of bits, this increases the rate at which the entropy pool must be refreshed with a call to keccak256(). TODO: benchmark higher number of bits for rejection vs hashing gas cost. */ function readLessThan( Source src, uint256 n, uint16 bits ) internal pure returns (uint256 result) { // Discard results >= n and try again because using % will bias towards // lower values; e.g. if n = 13 and we read 4 bits then {13, 14, 15}%13 // will select {0, 1, 2} twice as often as the other values. for (result = n; result >= n; result = read(src, bits)) {} } /** @notice Returns the internal state of the Source. @dev MUST NOT be considered part of the API and is subject to change without deprecation nor warning. Only exposed for testing. */ function state(Source src) internal pure returns ( uint256 seed, uint256 counter, uint256 entropy, uint256 remain ) { assembly { seed := mload(src) counter := mload(add(src, COUNTER)) entropy := mload(add(src, ENTROPY)) remain := mload(add(src, REMAIN)) } } /** @notice Stores the state of the Source in a 2-word buffer. See loadSource(). @dev The layout of the stored state MUST NOT be considered part of the public API, and is subject to change without warning. It is therefore only safe to rely on stored Sources _within_ contracts, but not _between_ them. */ function store(Source src, uint256[2] storage stored) internal { uint256 seed; // Counter will never be as high as 2^247 (because the sun will have // depleted by then) and remain is in [0,256], so pack them to save 20k // gas on an SSTORE. uint256 packed; assembly { seed := mload(src) packed := add( shl(9, mload(add(src, COUNTER))), mload(add(src, REMAIN)) ) } stored[0] = seed; stored[1] = packed; // Not storing the entropy as it can be recalculated later. } /** @notice Recreates a Source from the state stored with store(). */ function loadSource(uint256[2] storage stored) internal view returns (Source) { Source src = newSource(bytes32(stored[0])); uint256 packed = stored[1]; uint256 counter = packed >> 9; uint256 remain = packed & 511; assembly { mstore(add(src, COUNTER), counter) mstore(add(src, REMAIN), remain) // Has the same effect on internal state as as _refill() then // read(256-rem). let ent := shr(sub(256, remain), keccak256(src, 0x40)) mstore(add(src, ENTROPY), ent) } return src; } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; // Inspired by BaseOpenSea by Simon Fremaux (@dievardump) but without the need // to pass specific addresses depending on deployment network. // https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/ /// @notice Library to achieve gas-free listings on OpenSea. library OpenSeaGasFreeListing { /** @notice Returns whether the operator is an OpenSea proxy for the owner, thus allowing it to list without the token owner paying gas. @dev ERC{721,1155}.isApprovedForAll should be overriden to also check if this function returns true. */ function isApprovedForAll(address owner, address operator) internal view returns (bool) { ProxyRegistry registry; assembly { switch chainid() case 1 { // mainnet registry := 0xa5409ec958c83c3f309868babaca7c86dcb077c1 } case 4 { // rinkeby registry := 0xf57b2c51ded3a29e6891aba85459d600256cf317 } } return address(registry) != address(0) && address(registry.proxies(owner)) == operator; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "./ERC721Common.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; /** @notice Extends ERC721Common functionality with ERC721Enumerable. @dev This adds a significant gas cost to minting and transfers so only use if absolutely necessary. If only totalSupply() is needed and the contract is also an ethier Seller then use totalSold() as an alias. See: https://shiny.mirror.xyz/OUampBbIz9ebEicfGnQf5At_ReMHlZy0tB4glb9xQ0E */ contract ERC721CommonEnumerable is ERC721Common, ERC721Enumerable { constructor(string memory name, string memory symbol) ERC721Common(name, symbol) {} /** @notice Returns ERC721Common.isApprovedForAll() to guarantee use of OpenSea gas-free listing functionality. */ function isApprovedForAll(address owner, address operator) public view virtual override(ERC721, ERC721Common) returns (bool) { return ERC721Common.isApprovedForAll(owner, operator); } /// @notice Overrides _beforeTokenTransfer as required by inheritance. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Common, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /// @notice Overrides supportsInterface as required by inheritance. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Common, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "./OpenSeaGasFreeListing.sol"; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** @notice An ERC721 contract with common functionality: - OpenSea gas-free listings - OpenZeppelin Pausable - OpenZeppelin Pausable with functions exposed to Owner only */ contract ERC721Common is Context, ERC721Pausable, OwnerPausable { constructor(string memory name, string memory symbol) ERC721(name, symbol) {} /// @notice Requires that the token exists. modifier tokenExists(uint256 tokenId) { require(ERC721._exists(tokenId), "ERC721Common: Token doesn't exist"); _; } /// @notice Requires that msg.sender owns or is approved for the token. modifier onlyApprovedOrOwner(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Common: Not approved nor owner" ); _; } /// @notice Overrides _beforeTokenTransfer as required by inheritance. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /// @notice Overrides supportsInterface as required by inheritance. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } /** @notice Returns true if either standard isApprovedForAll() returns true or the operator is the OpenSea proxy for the owner. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return super.isApprovedForAll(owner, operator) || OpenSeaGasFreeListing.isApprovedForAll(owner, operator); } }
Sets addresses of icon-repository contracts.
function setRepository(EveryIconLib.Repository memory repo_) public onlyOwner repositoryUnlocked { repo = repo_; }
1,513,181
pragma solidity ^0.5.1; // Contract for buying and selling apratments or houses contract ApartmentContract { // Counts number of contracts, also used for contract ID uint256 public count = 0; // Contract has 3 states // Active - means still paying // Finished - means paid total sum // Cancelled - means buyer cancelled the contract enum Status {Cancelled, Finished, Active} // Apartment contract struct Apartment { uint256 id; string name; uint256 totalSum; uint256 paidSum; address payable seller; address payable buyer; Status status; } // Map of contracts // Key - Contract ID // Value - Contract information mapping(uint256 => Apartment) public apartments; // Event is called when a new contract created event ContractCreated( uint256 id, string name, uint256 totalSum, uint256 paidSum, address seller, address buyer, Status status ); // Event is called when a payment is transfered event ContractPayed( uint256 id, string name, uint256 totalSum, uint256 paidSum, address seller, Status status ); // Event is called when contract is finished (fully paid) event ContractFinished(uint256 id, string name, Status status); // Event is called when buyer cancels the contract event ContractCancelled(uint256 id, string name, Status status); // Constructor when the contract is first created // The contract "Test contract" is for tests constructor() public { createContract( "Test contract", 5, 0x090ec50a3f1184251E1041E5310F0f324FBD908E ); } // Function to create a new contract // _name - address of apartment or house // _totalSum - total sum in ether // _seller - address of seller function createContract( string memory _name, uint256 _totalSum, address payable _seller ) public { count++; apartments[count] = Apartment( count, _name, _totalSum, 0, _seller, msg.sender, Status.Active ); emit ContractCreated( count, _name, _totalSum, 0, _seller, msg.sender, Status.Active ); } // Function for paying to seller // _id - contract ID // The function is payable and the amount is transfered to seller and logged in paidSum function addPayment(uint256 _id) public payable { require(_id <= count); require(apartments[_id].status == Status.Active); apartments[_id].paidSum += msg.value; apartments[_id].seller.transfer(msg.value); if (apartments[_id].paidSum >= apartments[_id].totalSum) setFinished(_id); emit ContractPayed( _id, apartments[_id].name, apartments[_id].totalSum, apartments[_id].paidSum, apartments[_id].seller, apartments[_id].status ); } // Function to get the paid amount // _id - contract ID function getPaidSum(uint256 _id) public view returns (uint256) { return apartments[_id].paidSum; } // Function to get how much left to pay for the apartment or house // _id - contract ID function getDifference(uint256 _id) public view returns (uint256) { return apartments[_id].totalSum - apartments[_id].paidSum; } // Function to check if contract is active // _id - contract ID function isActive(uint256 _id) public view returns (bool) { return apartments[_id].status == Status.Active; } // Function to get contract status // _id - contract ID function getStatus(uint256 _id) public view returns (Status) { return apartments[_id].status; } // Function to cancel the contract and make it un-payable, only buyer can cancel it and only when it is active // _id - contract ID function setCancelled(uint256 _id) public { require(apartments[_id].status == Status.Active); require(apartments[_id].buyer == msg.sender); apartments[_id].status = Status.Cancelled; emit ContractCancelled( _id, apartments[_id].name, apartments[_id].status ); } // Function finish the contract and make it un-payable // It is private and can be called only from the function addPayment // _id - contract ID function setFinished(uint256 _id) private { apartments[_id].status = Status.Finished; emit ContractFinished( _id, apartments[_id].name, apartments[_id].status ); } }
Function for paying to seller _id - contract ID The function is payable and the amount is transfered to seller and logged in paidSum
function addPayment(uint256 _id) public payable { require(_id <= count); require(apartments[_id].status == Status.Active); apartments[_id].paidSum += msg.value; apartments[_id].seller.transfer(msg.value); if (apartments[_id].paidSum >= apartments[_id].totalSum) setFinished(_id); emit ContractPayed( _id, apartments[_id].name, apartments[_id].totalSum, apartments[_id].paidSum, apartments[_id].seller, apartments[_id].status ); }
13,009,993
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.7.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.7.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]. */ 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; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.7.0; /** * @title TokenRecover * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: contracts/token/IERC20Burnable.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC20Burnable. */ interface IERC20Burnable is IERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external; } // File: contracts/crowdsale/DripCrowdsale.sol pragma solidity ^0.7.0; contract DripCrowdsale is ReentrancyGuard, TokenRecover { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; IERC20Burnable private _token; address payable private _wallet; uint256 private _rate; uint256 private _weiRaised; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (uint256 rate, address payable wallet, IERC20Burnable token) { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } receive() external payable { buyTokens(_msgSender()); } function token() public view returns (IERC20Burnable) { return _token; } function wallet() public view returns (address payable) { return _wallet; } function rate() public view returns (uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _forwardFunds(); } function setRate(uint256 newRate) public onlyOwner { require(newRate > 0, "Crowdsale: rate is 0"); _rate = newRate; } function burnRemaining() public onlyOwner { _token.burn(_token.balanceOf(address(this))); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal virtual view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; } function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } function _getTokenAmount(uint256 weiAmount) internal virtual view returns (uint256) { return weiAmount.mul(_rate); } function _forwardFunds() internal virtual { _wallet.transfer(msg.value); } }
Interface of the ERC20Burnable./
interface IERC20Burnable is IERC20 { function burn(uint256 amount) external; }
10,507,481
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../../utils/Whitelistable.sol"; import "../../rarible/impl/RoyaltiesV2Impl.sol"; import "../../interfaces/IInflow1155BC.sol"; import "../../interfaces/ISocialToken.sol"; import "../../libraries/BondingCurveMath.sol"; import "../../libraries/FeeLib.sol"; contract Inflow1155BC is IInflow1155BC, ERC1155, ReentrancyGuard, Whitelistable, RoyaltiesV2Impl { using SafeERC20 for IERC20; using Counters for Counters.Counter; using FeeLib for uint256; ///////////////////////// /// STORAGE VARIABLES /// ///////////////////////// /// @dev Lock for contract accounts minting tokens bool private _contractMintEnabled; /// @dev Collateral token contract IERC20 public collateral; /// @dev Price to create an original token uint256 public createPrice = 50e6; /// @dev Funds reserved for burns uint256 public reserve; /// @dev TokenId counter Counters.Counter private _tokenIds; /// @dev Maps tokenId to Token struct mapping(uint256 => Token) private _tokens; /// @dev Base uri prepended to all token uris string public baseUri; constructor(address _collateral) ERC1155("") { collateral = IERC20(_collateral); } //////////////////////////////// /// EXTERNAL TOKEN FUNCTIONS /// //////////////////////////////// /// @dev Create an original token /// @param data (CreateData calldata): Struct containing data for minting origintal token /// @return tokenId (uint256): TokenId of minted token function create(CreateData calldata data) external override nonReentrant onlyWhitelist returns (uint256 tokenId) { data.curve == Curve.Const ? require(data.price > 0, "Inflow1155BC: needs non-zero price") : require(data.price == 0, "Inflow1155BC: needs zero price"); require(data.maxSupply > 0, "Inflow1155BC: invalid max supply"); require( data.royalties.length <= 16, "Inflow1155BC: invalid royalties length" ); _tokenIds.increment(); tokenId = _tokenIds.current(); Token storage token = _tokens[tokenId]; token.curve = data.curve; token.creator = msg.sender; token.social = ISocialToken(data.social); token.price = data.price; token.socialBalance = data.socialBalance; token.maxSupply = data.maxSupply; token.supply.increment(); token.uri = data.uri; _saveRoyalties(tokenId, data.royalties); _mint(msg.sender, tokenId, 1, ""); reserve += (createPrice * 85) / 100; collateral.safeTransferFrom(msg.sender, address(this), createPrice); emit Created( msg.sender, tokenId, data.curve, data.social, data.price, data.socialBalance, data.maxSupply, data.uri ); } /// @dev Mint a token /// @notice Contracts can bypass check if mint is called from a constructor /// @param tokenId (uint256): Numeric identifier of token function mint(uint256 tokenId) external override nonReentrant { if (Address.isContract(msg.sender)) { require( _contractMintEnabled, "Inflow1155BC: minting from contracts disabled" ); } Token storage token = _tokens[tokenId]; require( token.social.balanceOf(msg.sender) >= token.socialBalance, "Inflow1155BC: insufficient social token balance" ); token.supply.increment(); uint256 newSupply = token.supply.current(); uint256 mintPrice = token.curve == Curve.Const ? token.price : getMintPrice(token.curve, newSupply); uint256 burnPrice = token.curve == Curve.Const ? (mintPrice * 85) / 100 : getBurnPrice(token.curve, newSupply); reserve += burnPrice; uint256 creatorFee = getCreatorFee(mintPrice - burnPrice); _mint(msg.sender, tokenId, 1, ""); IERC20 _collateral = collateral; _collateral.safeTransferFrom(msg.sender, address(this), mintPrice); _transferCreatorFee(tokenId, creatorFee); emit Minted( msg.sender, tokenId, mintPrice, token.curve == Curve.Const ? token.price : getMintPrice(token.curve, newSupply + 1), burnPrice, newSupply, creatorFee, reserve, token.creator ); } /// @dev Burn a token /// @param tokenId (uint256): Numeric identifier of token /// @param minimumSupply (uint256): The minimum token supply for burn to succeed, this is a way to set slippage. Set minimumSupply to 1 to allow burn to go through no matter the mint price function burn(uint256 tokenId, uint256 minimumSupply) external override nonReentrant { Token storage token = _tokens[tokenId]; require(token.creator != address(0), "Inflow1155BC: token does not exist"); uint256 supply = token.supply.current(); require(supply >= minimumSupply, "Inflow1155BC: invalid minimum supply"); uint256 burnPrice = token.curve == Curve.Const ? (token.price * 85) / 100 : getBurnPrice(token.curve, supply); token.supply.decrement(); uint256 newSupply = token.supply.current(); reserve -= burnPrice; if (newSupply == 0) delete _tokens[tokenId]; _burn(msg.sender, tokenId, 1); collateral.safeTransfer(msg.sender, burnPrice); emit Burned( msg.sender, tokenId, burnPrice, token.curve == Curve.Const ? token.price : getMintPrice(token.curve, supply), token.curve == Curve.Const ? (token.price * 85) / 100 : getBurnPrice(token.curve, newSupply), newSupply, reserve ); } //////////////////////////////////// /// EXTERNAL ROYALTIES FUNCTIONS /// //////////////////////////////////// /// @dev Update address of a royalty account /// @notice Sender must be current royalty account /// @param tokenId (uint256): Numeric identifier of token /// @param from (address): Old royalty account's address /// @param to (address): New royalty account's address function updateRoyaltyAccount( uint256 tokenId, address from, address to ) external override { require(msg.sender == from, "Inflow1155BC: only current royalty account"); _updateAccount(tokenId, from, to); } ///////////////////////////////// /// EXTERNAL GETTER FUNCTIONS /// ///////////////////////////////// /// @dev Returns Token struct at tokenId /// @param tokenId (uint256): Numeric identifier of token /// @return (Token memory): Token struct at tokenId function getToken(uint256 tokenId) external view override returns (Token memory) { require(tokenId > 0, "Inflow1155BC: getToken query for tokenId zero"); return _tokens[tokenId]; } //////////////////////////////// /// EXTERNAL ADMIN FUNCTIONS /// //////////////////////////////// /// @dev Withdraw earned funds from create and mint fees /// @notice Cannot withdraw the reserve funds function withdraw() external override onlyOwner nonReentrant { IERC20 _collateral = collateral; uint256 withdrawableFunds = _collateral.balanceOf(address(this)) - reserve; _collateral.safeTransfer(msg.sender, withdrawableFunds); } /// @dev Set the price for minting an original token /// @param price (uint256): New price to mint an original token function setCreatePrice(uint256 price) external override onlyOwner { createPrice = price; } /// @dev Enable/disable mint from a contract /// @param enabled (bool): Flag to turn mint from a contract on or off function setContractMintEnabled(bool enabled) external override onlyOwner { _contractMintEnabled = enabled; } /// @dev Set the base uri for all tokens /// @param _baseUri (string calldata): New base uri string /// Prepended to result of {uri} or to the tokenId if {_tokens[tokenId].uri} is empty function setBaseUri(string calldata _baseUri) external override onlyOwner { baseUri = _baseUri; } ////////////////////////////// /// PUBLIC PRICE FUNCTIONS /// ////////////////////////////// /// @dev Calculate price of next minted token /// @param curve (Curve): Bonding curve id /// @param supply (uint256): The token supply after then next minting Ex. if there are 2 existing images, and you want to get the next image price, then this should be 3 as you are getting the price to mint the 3rd image /// @return price (uint256): Calculated price for given curve and supply function getMintPrice(Curve curve, uint256 supply) public pure override returns (uint256 price) { if (curve == Curve.Lin) price = BondingCurveMath.lin(supply); else if (curve == Curve.Exp) price = BondingCurveMath.exp(supply); price *= 1e6; } /// @dev Calculate funds received on burn /// @param curve (Curve): Bonding curve id /// @param supply (uint256): The supply of images before burning. Ex. if there are 2 existing images, to get the funds receive on burn the supply should be 2 /// @return uint256 function getBurnPrice(Curve curve, uint256 supply) public pure override returns (uint256) { uint256 mintPrice = getMintPrice(curve, supply); return (mintPrice * 85) / 100; } /// @dev Calculate creator's royalty /// @param fee (uint256): Total fee frm which to calculate creator's royalty fee /// @return (uint256): Creator's royalty function getCreatorFee(uint256 fee) public pure override returns (uint256) { return (fee * 8) / 10; } //////////////////////////// /// PUBLIC URI FUNCTIONS /// //////////////////////////// /// @dev Returns token's uri /// @param tokenId (uint256): Numeric identifier of token /// @return _uri (string memory) function uri(uint256 tokenId) public view virtual override returns (string memory _uri) { Token memory token = _tokens[tokenId]; require(token.creator != address(0), "Inflow1155BC: token does not exist"); string memory base = baseUri; if (bytes(base).length == 0) { _uri = token.uri; } else if (bytes(token.uri).length > 0) { _uri = string(abi.encodePacked(base, token.uri)); } else { _uri = string(abi.encodePacked(base, Strings.toString(tokenId))); } } ////////////////////////////////////// /// PUBLIC INTROSPECTION FUNCTIONS /// ////////////////////////////////////// /// @dev Checks if contract supports interface /// @param interfaceId (bytes4): Interface selector /// @return bool function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IERC165) returns (bool) { return ERC1155.supportsInterface(interfaceId); } ////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////// /// @dev Transfer creator fees /// @param tokenId (uint256): Numeric identifier of token /// @param creatorFee (uint256): Total fee owed to creator(s) function _transferCreatorFee(uint256 tokenId, uint256 creatorFee) internal { LibPart.Part[] memory fees = royalties[tokenId]; uint256 owed = creatorFee; IERC20 _collateral = collateral; for (uint256 i = 0; i < fees.length; i++) { (uint256 remaining, uint256 fee) = owed.subFeeInBp( creatorFee, fees[i].value ); owed = remaining; if (fee > 0) _collateral.safeTransfer(fees[i].account, fee); } } }
Withdraw earned funds from create and mint fees Cannot withdraw the reserve funds
function withdraw() external override onlyOwner nonReentrant { IERC20 _collateral = collateral; uint256 withdrawableFunds = _collateral.balanceOf(address(this)) - reserve; _collateral.safeTransfer(msg.sender, withdrawableFunds); }
14,079,059
./partial_match/4/0xC6328322A3b44412bCf763e53A92efAfB0a978d3/sources/FarmContract.sol
(paperBlance + debt) (totalLP - amount) / totalLP - paperBalance (paperBalance + debt) user.amount / totalLP
function withdraw(uint256 _amount) public { require(paper.totalSupply() == paper.maxSupply(), "Withdrawals will be available after PAPER max supply is reached"); require(users[msg.sender].amount >= _amount, "You don't have enough LP tokens"); require(paperWethLP.balanceOf(address(this)) > 0, "No tokens left"); harvest(); debt = paper.balanceOf(address(this)).add(debt).mul(paperWethLP.balanceOf(address(this)).sub(_amount)).div(paperWethLP.balanceOf(address(this))); if (debt > paper.balanceOf(address(this))) { debt = debt.sub(paper.balanceOf(address(this))); debt = 0; } paperWethLP.safeTransfer(address(msg.sender), _amount); if (users[msg.sender].amount > _amount) { users[msg.sender].amount = users[msg.sender].amount.sub(_amount); users[msg.sender].amount = 0; } if (paperWethLP.balanceOf(address(this)) > 0) { users[msg.sender].loss = paper.balanceOf(address(this)).add(debt).mul(users[msg.sender].amount).div(paperWethLP.balanceOf(address(this))); users[msg.sender].loss = 0; } }
8,522,328
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import "./libraries/Data.sol"; import "./libraries/Fork.sol"; import "./libraries/ForkDeposit.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IDestinationContract.sol"; import "./MessageDock/CrossDomainHelper.sol"; import "./PoolTokenApprovable.sol"; import "hardhat/console.sol"; contract NewDestination is IDestinationContract, CrossDomainHelper, Ownable, PoolTokenApprovable { using SafeERC20 for IERC20; using HashOnions for mapping(uint256 => HashOnions.Info); using Fork for mapping(bytes32 => Fork.Info); using ForkDeposit for mapping(bytes32 => ForkDeposit.Info); address private tokenAddress; mapping(bytes32 => Fork.Info) public hashOnionForks; mapping(uint256 => mapping(bytes32 => bool)) private isRespondOnions; mapping(uint256 => HashOnions.Info) private hashOnions; mapping(bytes32 => address) private onionsAddress; // !!! Conflict with using zk scheme, new scheme needs to be considered when using zk mapping(address => uint256) private source_chainIds; mapping(address => bool) private _committerDeposits; // Submitter's bond record mapping(bytes32 => ForkDeposit.Info) private hashOnionForkDeposits; uint256 public immutable ONEFORK_MAX_LENGTH = 5; // !!! The final value is 50 , the higher the value, the longer the wait time and the less storage consumption uint256 public immutable DEPOSIT_AMOUNT = 1 * 10**18; // !!! The final value is 2 * 10**17 /* 1. every LP need deposit `DEPOSIT_AMOUNT` ETH, DEPOSIT_AMOUNT = OnebondGaslimit * max_fork.length * Average_gasPrice 2. when LP call zfork()、mfork()、claim(). lock deposit, and unlock the preHashOnions LP's deposit. 3. When bonder is settling `middle fork`, will get `DEPOSIT_AMOUNT` ETH back from destContract. 4. LP's deposit can only be withdrawn if they are unlocked. 5. No one wants to pay for someone else's mistakes, so the perpetrator's deposit will never be unlocked */ constructor(address _tokenAddress, address _dockAddr) CrossDomainHelper(_dockAddr) { tokenAddress = _tokenAddress; } function _onlyApprovedSources(address _sourceSender, uint256 _sourChainId) internal view override { require(_sourChainId != 0, "ZERO_CHAINID"); require(source_chainIds[_sourceSender] == _sourChainId, "NOTAPPROVE"); } /* * call from source * TODO it is not already ok */ function bondSourceHashOnion(uint256 chainId, bytes32 hashOnion) external sourceSafe { HashOnions.Info memory info = hashOnions[chainId]; if (info.onWorkHashOnion == "" || info.onWorkHashOnion == hashOnion) { hashOnions[chainId].onWorkHashOnion = hashOnion; } hashOnions[chainId].sourceHashOnion = hashOnion; } /** * Add domain. Init hashOnionForks, bind source & chainId */ function addDomain(uint256 chainId, address source) external onlyOwner { hashOnionForks.initialize(chainId, ONEFORK_MAX_LENGTH); source_chainIds[source] = chainId; } // TODO need deposit ETH function becomeCommiter() external { _committerDeposits[msg.sender] = true; } function getHashOnionFork( uint256 chainId, bytes32 hashOnion, uint16 index ) external view returns (Fork.Info memory) { bytes32 forkKey = Fork.generateForkKey(chainId, hashOnion, index); return hashOnionForks.getForkEnsure(forkKey); } function getHashOnionInfo(uint256 chainId) external view returns (HashOnions.Info memory) { return hashOnions[chainId]; } /* A. Ensure that a single correct fork link is present: There are three behaviors of commiters related to fork: 1. Create a 0-bit fork 2. Create a non-zero fork 3. Add OnionHead to any Fork The rules are as follows: 1. Accept any submission, zero-bit Fork needs to pass in PreForkkey 2. Fork starting with non-zero bits, length == ONEFORK_MAX_LENGTH - index (value range 1-49) B. Ensure that only the only correct fork link will be settled: 1. onWorkHashOnion's index % ONEFORK_MAX_LENGTH == ONEFORK_MAX_LENGTH 2. When bonding, the bond is the bond from the back to the front. If the fork being bonded is a non-zero fork, you need to provide preForkKey, onions1, onions2, and the parameters must meet the following conditions: 2.1 f(onions) == preFork.onionHead 2.2 onions[0] != fork.key //If there is an equal situation, then give the allAmount of the fork to onions[0].address . The bonder gets a deposit to compensate the gas fee. 2.3 fork.onionHead == onWorkHashOnion C. Guarantee that bad commits will be penalized: 1. CommiterA deposits the deposit, initiates a commit or fork, and the deposit is locked 2. The margin can only be unlocked by the addition of another Committer */ // if index % ONEFORK_MAX_LENGTH == 0 function zFork( uint256 chainId, bytes32 workForkKey, address dest, uint256 amount, uint256 fee, bool _isRespond ) external override { (Fork.Info memory workFork, Fork.Info memory newFork) = hashOnionForks .createZFork(chainId, workForkKey, dest, amount, fee); if (_committerDeposits[msg.sender] == false) { // If same commiter, don't need deposit require(msg.sender == workFork.lastCommiterAddress, "a2"); } // Determine whether the maker only submits or submits and responds if (_isRespond) { IERC20(tokenAddress).safeTransferFrom(msg.sender, dest, amount); } else { // !!! Whether to add the identification position of the index isRespondOnions[chainId][newFork.onionHead] = true; } // Locks the new committer's bond, unlocks the previous committer's bond state if (workFork.lastCommiterAddress != msg.sender) { _committerDeposits[workFork.lastCommiterAddress] = true; _committerDeposits[msg.sender] = false; } emit newClaim(dest, amount, fee, 0, newFork.onionHead); } // just deppend function claim( uint256 chainId, bytes32 workForkKey, uint256 _workIndex, Data.TransferData[] calldata _transferDatas, bool[] calldata _isResponds ) external override { // incoming data length is correct require(_transferDatas.length > 0, "a1"); Fork.Info memory workFork = hashOnionForks.getForkEnsure(workForkKey); // Determine the eligibility of the submitter if (_committerDeposits[msg.sender] == false) { require(msg.sender == workFork.lastCommiterAddress, "a3"); } // Determine whether someone has submitted it before. If it has been submitted by the predecessor, tx.origin thinks that the submission is incorrect and can be forked and resubmitted through forkFromInput // !!! Avoid duplicate submissions require(_workIndex == workFork.length, "b2"); // Judge _transferDatas not to exceed the limit require(_workIndex + _transferDatas.length <= ONEFORK_MAX_LENGTH, "a2"); bytes32 onionHead = workFork.onionHead; bytes32 destOnionHead = workFork.destOnionHead; uint256 allAmount = 0; // just append for (uint256 i; i < _transferDatas.length; i++) { onionHead = Fork.generateOnionHead(onionHead, _transferDatas[i]); if (_isResponds[i]) { IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferDatas[i].destination, _transferDatas[i].amount ); } else { // TODO need change to transferData hash isRespondOnions[chainId][onionHead] = true; } destOnionHead = Fork.generateDestOnionHead( destOnionHead, onionHead, msg.sender ); allAmount += _transferDatas[i].amount + _transferDatas[i].fee; emit newClaim( _transferDatas[i].destination, _transferDatas[i].amount, _transferDatas[i].fee, _workIndex + i, onionHead ); } // change deposit , deposit token is ETH , need a function to deposit and with draw if (workFork.lastCommiterAddress != msg.sender) { _committerDeposits[workFork.lastCommiterAddress] = true; _committerDeposits[msg.sender] = false; } workFork = Fork.Info( 0, onionHead, destOnionHead, allAmount + workFork.allAmount, _workIndex + _transferDatas.length, msg.sender, workFork.needBond, 0 ); // storage hashOnionForks.update(workForkKey, workFork); } // if source index % ONEFORK_MAX_LENGTH != 0 function mFork( uint256 chainId, bytes32 _lastOnionHead, bytes32 _lastDestOnionHead, uint16 _index, Data.TransferData calldata _transferData, bool _isRespond ) external override { // Determine whether tx.origin is eligible to submit require(_committerDeposits[msg.sender] == true, "a3"); Fork.Info memory newFork = hashOnionForks.createMFork( chainId, _lastOnionHead, _lastDestOnionHead, _index, _transferData ); // Determine whether the maker only submits or submits and also responds, so as to avoid the large amount of unresponsiveness of the maker and block subsequent commints if (_isRespond) { IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferData.destination, _transferData.amount ); } else { isRespondOnions[chainId][newFork.onionHead] = true; } // Freeze Margin _committerDeposits[msg.sender] = false; } // clearing zfork function zbond( uint256 chainId, bytes32 prevForkKey, bytes32 forkKey, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) external override { // incoming data length is correct require(_transferDatas.length > 0, "a1"); require(_committers.length == _transferDatas.length, "a2"); Fork.Info memory workFork = hashOnionForks.getForkEnsure(forkKey); bool isEarlyBonded = Fork.isEarlyBonded( workFork.verifyStatus, workFork.needBond ); // When verified and not needBond, throw error require(workFork.verifyStatus == 0 || workFork.needBond, "a3"); // Determine whether the onion of the fork has been recognized require( workFork.onionHead == hashOnions[chainId].onWorkHashOnion, "a4" ); Fork.Info memory prevWorkFork = hashOnionForks.getForkEnsure( prevForkKey ); (bytes32[] memory onionHeads, bytes32 destOnionHead) = Fork .getVerifyOnions(prevWorkFork, _transferDatas, _committers); // Assert that the replay result is equal to the stored value of the fork, which means that the incoming _transferdatas are valid require(destOnionHead == workFork.destOnionHead, "a5"); // storage workFork workFork.verifyStatus = 1; workFork.needBond = false; hashOnionForks.update(forkKey, workFork); // If the prefork also needs to be settled, push the onWorkHashOnion forward a fork _setOnWorkHashOnion(chainId, prevWorkFork); // When earlyBonded, donnot transfer to committers if (isEarlyBonded) { return; } _settlement( chainId, workFork.allAmount, onionHeads, _transferDatas, _committers ); // When has forkDeposit, send token to fork's endorser ForkDeposit.Info memory forkDeposit = hashOnionForkDeposits[forkKey]; if (forkDeposit.endorser != address(0)) { IERC20(tokenAddress).safeTransfer( forkDeposit.endorser, forkDeposit.amount // TODO Add reward and denyer amount ); } // !!! Reward bonder } function buyOneOnion( uint256 chainId, bytes32 preHashOnion, Data.TransferData calldata _transferData ) external override { bytes32 key = keccak256( abi.encode(preHashOnion, keccak256(abi.encode(_transferData))) ); require(isRespondOnions[chainId][key], "a1"); require(onionsAddress[key] == address(0), "a2"); IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferData.destination, _transferData.amount ); onionsAddress[key] = msg.sender; } // Depostit one fork function depositWithOneFork(bytes32 forkKey) public { Fork.Info memory fork = hashOnionForks.getForkEnsure(forkKey); require(fork.workIndex == 0, "Only zFork"); require(fork.length == ONEFORK_MAX_LENGTH, "Insufficient length"); uint256 amount = fork.allAmount / ForkDeposit.DEPOSIT_SCALE; IERC20(tokenAddress).safeTransferFrom( msg.sender, address(this), amount ); hashOnionForkDeposits.deposit(forkKey, amount, false); // Event } // Deposit mForks function depositMForks( uint256 chainId, bytes32 _prevForkKey, Data.MForkData[] calldata _mForkDatas, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) external { require( _transferDatas.length == ONEFORK_MAX_LENGTH, "Insufficient length" ); Fork.Info memory prevFork = hashOnionForks.getForkEnsure(_prevForkKey); // Create unitedForkKey bytes32 hashOnion = Fork.generateOnionHead( prevFork.onionHead, _transferDatas[0] ); bytes32 unitedForkKey = Fork.generateForkKey( chainId, hashOnion, ForkDeposit.MFORK_UNITED_WORK_INDEX ); uint256 allAmount = 0; uint16 fi = 0; for (uint16 i = 0; i < _transferDatas.length; i++) { Data.TransferData memory transferData = _transferDatas[i]; allAmount += transferData.amount + transferData.fee; if (fi < _mForkDatas.length && _mForkDatas[fi].forkIndex == i) { // Ensure fork exist require( hashOnionForks.isExist(_mForkDatas[fi].forkKey), "Fork is null" ); fi += 1; } } Fork.Info memory unitedFork; unitedFork.allAmount = allAmount; unitedFork.length = ONEFORK_MAX_LENGTH; unitedFork.needBond = true; // Set onionHead, destOnionHead and lastCommiterAddress bytes32 onionHead = prevFork.onionHead; bytes32 destOnionHead = prevFork.destOnionHead; for (uint256 i; i < _transferDatas.length; i++) { onionHead = Fork.generateOnionHead(onionHead, _transferDatas[i]); destOnionHead = Fork.generateDestOnionHead( destOnionHead, onionHead, _committers[i] ); unitedFork.lastCommiterAddress = _committers[i]; } unitedFork.onionHead = onionHead; unitedFork.destOnionHead = destOnionHead; hashOnionForks.update(unitedForkKey, unitedFork); depositWithOneFork(unitedForkKey); } // Deny depostit one fork function denyDepositOneFork(bytes32 forkKey) external { ForkDeposit.Info memory forkDeposit = hashOnionForkDeposits .getDepositEnsure(forkKey); IERC20(tokenAddress).safeTransferFrom( msg.sender, address(this), forkDeposit.amount ); hashOnionForkDeposits.deposit(forkKey, forkDeposit.amount, true); } function earlyBond( uint256 chainId, bytes32 prevForkKey, bytes32 forkKey, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) external { ForkDeposit.Info memory forkDeposit = hashOnionForkDeposits .getDepositEnsure(forkKey); require(forkDeposit.denyer == address(0), "Dispute"); require( ForkDeposit.isBlockNumberArrive(forkDeposit.prevBlockNumber), "No arrive" ); Fork.Info memory prevFork = hashOnionForks.getForkEnsure(prevForkKey); Fork.Info memory fork = hashOnionForks.getForkEnsure(forkKey); require(fork.verifyStatus == 0, "Invalid verifyStatus"); // Check destOnionHead (bytes32[] memory onionHeads, bytes32 destOnionHead) = Fork .getVerifyOnions(prevFork, _transferDatas, _committers); require(destOnionHead == fork.destOnionHead, "Different destOnionHead"); _settlement( chainId, fork.allAmount, onionHeads, _transferDatas, _committers ); // Send token to fork's endorser IERC20(tokenAddress).safeTransfer( forkDeposit.endorser, forkDeposit.amount // TODO Add reward(No denyer here) ); // storage fork fork.needBond = false; hashOnionForks.update(forkKey, fork); } function disputeSolve( uint256 chainId, bytes32 prevForkKey, bytes32 forkKey, bytes32 forkTxHash, bytes32[] memory wrongForkKeys, bytes32[] memory wrongForkTxHashs ) external { Fork.Info memory prevFork = hashOnionForks.getForkEnsure(prevForkKey); Fork.Info memory fork = hashOnionForks.getForkEnsure(forkKey); // Verify forkKey bytes32 forkOnionHead = keccak256( abi.encode(prevFork.onionHead, forkTxHash) ); require( Fork.generateForkKey(chainId, forkOnionHead, fork.workIndex) == forkKey, "ForkKey verify faild" ); require(fork.verifyStatus == 1, "Fork verify failed"); bytes32 wrongForkOnionHead = prevFork.onionHead; for (uint256 i = 0; i < wrongForkKeys.length; i++) { Fork.Info memory wrongFork = hashOnionForks.getForkEnsure( wrongForkKeys[i] ); // Verify wrong forkKey, verifyStatus wrongForkOnionHead = keccak256( abi.encode(wrongForkOnionHead, wrongForkTxHashs[i]) ); require( Fork.generateForkKey( chainId, wrongForkOnionHead, wrongFork.workIndex ) == wrongForkKeys[i], "Wrong forkKey verify faild" ); require(wrongFork.verifyStatus != 0, "Exception verifyStatus"); // Check deposit ForkDeposit.Info memory wrongForkDeposit = hashOnionForkDeposits .getDepositEnsure(wrongForkKeys[i]); require(wrongForkDeposit.denyer != address(0), "No exist denyer"); IERC20(tokenAddress).safeTransfer( wrongForkDeposit.denyer, wrongForkDeposit.amount ); // Change wrongFork.verifyStatus wrongFork.verifyStatus = 2; hashOnionForks.update(wrongForkKeys[i], wrongFork); } } function loanFromLPPool(uint256 amount) internal { // Send bondToken to LPPool, LPPool send real token to dest PoolToken(poolTokenAddress()).exchange(tokenAddress, amount); } // buy bond token function buyOneFork( uint256 chainId, uint256 _forkKey, uint256 _forkId ) external override {} // 1. Dest borrow token from the liquidity poo.(When liquidity is insufficient) // 2. Dest send token to committers function _settlement( uint256 chainId, uint256 forkAllAmount, bytes32[] memory onionHeads, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) internal { // When token.balanceOf(this) < fork.allAmount, get token from LP if (IERC20(tokenAddress).balanceOf(address(this)) < forkAllAmount) { uint256 diffAmount = forkAllAmount - IERC20(tokenAddress).balanceOf(address(this)); // Ensure LP has sufficient token require( IERC20(tokenAddress).balanceOf(poolTokenAddress()) >= diffAmount, "Pool insufficient" ); // Calculate lever PoolToken poolToken = PoolToken(poolTokenAddress()); uint256 poolTokenAmount = diffAmount / poolToken.scale(); // TODO Debug, mint poolToken poolToken.mint(poolTokenAmount); // Exchange poolToken.exchange(tokenAddress, poolTokenAmount); } // Send token to committers for (uint256 i; i < _transferDatas.length; i++) { bytes32 onionHead = onionHeads[i]; if (isRespondOnions[chainId][onionHead]) { address onionAddress = onionsAddress[onionHead]; if (onionAddress != address(0)) { IERC20(tokenAddress).safeTransfer( onionAddress, _transferDatas[i].amount + _transferDatas[i].fee ); } else { IERC20(tokenAddress).safeTransfer( _transferDatas[i].destination, _transferDatas[i].amount + _transferDatas[i].fee ); } } else { IERC20(tokenAddress).safeTransfer( _committers[i], _transferDatas[i].amount + _transferDatas[i].fee ); } } } function _setOnWorkHashOnion(uint256 chainId, Fork.Info memory fork) internal { HashOnions.Info memory info = hashOnions[chainId]; if ( fork.needBond || Fork.isEarlyBonded(fork.verifyStatus, fork.needBond) ) { info.onWorkHashOnion = fork.onionHead; } else { // If no settlement is required, it means that the previous round of settlement is completed, and a new value is set info.onWorkHashOnion = info.sourceHashOnion; } hashOnions[chainId] = info; } }
Send bondToken to LPPool, LPPool send real token to dest
function loanFromLPPool(uint256 amount) internal { PoolToken(poolTokenAddress()).exchange(tokenAddress, amount); }
5,533,116
./partial_match/42/0xC31518D4fbA20E3618F6e7B24D1Bada43837Ed45/sources/GebProxyDebtAuctionActions.sol
Exits Coin to proxy owner coinJoin CoinJoin wad Amount to exit Allows adapter to access to proxy's COIN balance in the safeEngine
function exitCoin(address coinJoin, uint wad) public { if (CoinJoinLike(coinJoin).safeEngine().canModifySAFE(address(this), address(coinJoin)) == 0) { CoinJoinLike(coinJoin).safeEngine().approveSAFEModification(coinJoin); } CoinJoinLike(coinJoin).exit(msg.sender, wad); }
3,338,866
/** * Source Code first verified at https://etherscan.io * WorldTrade asset Smart Contract v4.1 */ pragma solidity ^0.4.16; /* * @title Standard Token Contract * * ERC20-compliant tokens => https://github.com/ethereum/EIPs/issues/20 * A token is a fungible virtual good that can be traded. * ERC-20 Tokens comply to the standard described in the Ethereum ERC-20 proposal. * Basic, standardized Token contract. Defines the functions to check token balances * send tokens, send tokens on behalf of a 3rd party and the corresponding approval process. * */ contract Token { // **** BASE FUNCTIONALITY // @notice For debugging purposes when using solidity online browser function whoAmI() constant returns (address) { return msg.sender; } // SC owners: address owner; function isOwner() returns (bool) { if (msg.sender == owner) return true; return false; } // **** EVENTS // @notice A generic error log event Error(string error); // **** DATA mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public initialSupply; // Initial and total token supply uint256 public totalSupply; // bool allocated = false; // True after defining token parameters and initial mint // Public variables of the token, all used for display // HumanStandardToken is a specialisation of ERC20 defining these parameters string public name; string public symbol; uint8 public decimals; string public standard = 'H0.1'; // **** METHODS // Get total amount of tokens, totalSupply is a public var actually // function totalSupply() constant returns (uint256 totalSupply) {} // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Send _amount amount of tokens to address _to function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] < _amount) { Error('transfer: the amount to transfer is higher than your token balance'); return false; } balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } // Send _amount amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { if (balances[_from] < _amount) { Error('transfer: the amount to transfer is higher than the token balance of the source'); return false; } if (allowed[_from][msg.sender] < _amount) { Error('transfer: the amount to transfer is higher than the maximum token transfer allowed by the source'); return false; } balances[_from] -= _amount; balances[_to] += _amount; allowed[_from][msg.sender] -= _amount; Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _amount amount. // If this function is called again it overwrites the current allowance with _amount. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Constructor: set up token properties and owner token balance function Token() { // This is the constructor, so owner should be equal to msg.sender, and this method should be called just once owner = msg.sender; // make sure owner address is configured // if(owner == 0x0) throw; // owner address can call this function // if (msg.sender != owner ) throw; // call this function just once // if (allocated) throw; initialSupply = 50000000 * 1000000; // 50M tokens, 6 decimals totalSupply = initialSupply; name = "WorldTrade"; symbol = "WTE"; decimals = 6; balances[owner] = totalSupply; Transfer(this, owner, totalSupply); // allocated = true; } // **** EVENTS // Triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called event Approval(address indexed _owner, address indexed _spender, uint256 _amount); } // Interface of issuer contract, just to cast the contract address and make it callable from the asset contract contract IFIssuers { // **** DATA // **** FUNCTIONS function isIssuer(address _issuer) constant returns (bool); } contract Asset is Token { // **** DATA /** Asset states * * - Released: Once issued the asset stays as released until sent for free to someone specified by issuer * - ForSale: The asset belongs to a user and is open to be sold * - Unfungible: The asset cannot be sold, remaining to the user it belongs to. */ enum assetStatus { Released, ForSale, Unfungible } // https://ethereum.stackexchange.com/questions/1807/enums-in-solidity struct asst { uint256 assetId; address assetOwner; address issuer; string content; // a JSON object containing the image data of the asset and its title uint256 sellPrice; // in WorldTrade tokens, how many of them for this asset assetStatus status; // behaviour (tradability) of the asset depends upon its status } mapping (uint256 => asst) assetsById; uint256 lastAssetId; // Last assetId address public SCIssuers; // Contract that defines who is an issuer and who is not uint256 assetFeeIssuer; // Fee percentage for Issuer on every asset sale transaction uint256 assetFeeWorldTrade; // Fee percentage for WorldTrade on every asset sale transaction // **** METHODS // Constructor function Asset(address _SCIssuers) { SCIssuers = _SCIssuers; } // Queries the asset, knowing the id function getAssetById(uint256 assetId) constant returns (uint256 _assetId, address _assetOwner, address _issuer, string _content, uint256 _sellPrice, uint256 _status) { return (assetsById[assetId].assetId, assetsById[assetId].assetOwner, assetsById[assetId].issuer, assetsById[assetId].content, assetsById[assetId].sellPrice, uint256(assetsById[assetId].status)); } // Seller sends an owned asset to a buyer, providing its allowance matches token price and transfer the tokens from buyer function sendAssetTo(uint256 assetId, address assetBuyer) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('sendAssetTo: assetId must not be zero'); return false; } // Check whether the asset belongs to the seller if (assetsById[assetId].assetOwner != msg.sender) { Error('sendAssetTo: the asset does not belong to you, the seller'); return false; } if (assetsById[assetId].sellPrice > 0) { // for non-null token paid transactions // Check whether there is balance enough from the buyer to get its tokens if (balances[assetBuyer] < assetsById[assetId].sellPrice) { Error('sendAssetTo: there is not enough balance from the buyer to get its tokens'); return false; } // Check whether there is allowance enough from the buyer to get its tokens if (allowance(assetBuyer, msg.sender) < assetsById[assetId].sellPrice) { Error('sendAssetTo: there is not enough allowance from the buyer to get its tokens'); return false; } // Get the buyer tokens if (!transferFrom(assetBuyer, msg.sender, assetsById[assetId].sellPrice)) { Error('sendAssetTo: transferFrom failed'); // This shouldn't happen ever, but just in case... return false; } } // Set the asset status to Unfungible assetsById[assetId].status = assetStatus.Unfungible; // Transfer the asset to the buyer assetsById[assetId].assetOwner = assetBuyer; // Event log SendAssetTo(assetId, assetBuyer); return true; } // Buyer gets an asset providing it is in ForSale status, and pays the corresponding tokens to the seller/owner. amount must match assetPrice to have a deal. function buyAsset(uint256 assetId, uint256 amount) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('buyAsset: assetId must not be zero'); return false; } // Check whether the asset is in ForSale status if (assetsById[assetId].status != assetStatus.ForSale) { Error('buyAsset: the asset is not for sale'); return false; } // Check whether the asset price is the same as amount if (assetsById[assetId].sellPrice != amount) { Error('buyAsset: the asset price does not match the specified amount'); return false; } if (assetsById[assetId].sellPrice > 0) { // for non-null token paid transactions // Check whether there is balance enough from the buyer to pay the asset if (balances[msg.sender] < assetsById[assetId].sellPrice) { Error('buyAsset: there is not enough token balance to buy this asset'); return false; } // Calculate the seller income uint256 sellerIncome = assetsById[assetId].sellPrice * (1000 - assetFeeIssuer - assetFeeWorldTrade) / 1000; // Send the buyer's tokens to the seller if (!transfer(assetsById[assetId].assetOwner, sellerIncome)) { Error('buyAsset: seller token transfer failed'); // This shouldn't happen ever, but just in case... return false; } // Send the issuer's fee uint256 issuerIncome = assetsById[assetId].sellPrice * assetFeeIssuer / 1000; if (!transfer(assetsById[assetId].issuer, issuerIncome)) { Error('buyAsset: issuer token transfer failed'); // This shouldn't happen ever, but just in case... return false; } // Send the WorldTrade's fee uint256 WorldTradeIncome = assetsById[assetId].sellPrice * assetFeeWorldTrade / 1000; if (!transfer(owner, WorldTradeIncome)) { Error('buyAsset: WorldTrade token transfer failed'); // This shouldn't happen ever, but just in case... return false; } } // Set the asset status to Unfungible assetsById[assetId].status = assetStatus.Unfungible; // Transfer the asset to the buyer assetsById[assetId].assetOwner = msg.sender; // Event log BuyAsset(assetId, amount); return true; } // To limit issue functions just to authorized issuers modifier onlyIssuer() { if (!IFIssuers(SCIssuers).isIssuer(msg.sender)) { Error('onlyIssuer function called by user that is not an authorized issuer'); } else { _; } } // To be called by issueAssetTo() and properly authorized issuers function issueAsset(string content, uint256 sellPrice) onlyIssuer internal returns (uint256 nextAssetId) { // Find out next asset Id nextAssetId = lastAssetId + 1; assetsById[nextAssetId].assetId = nextAssetId; assetsById[nextAssetId].assetOwner = msg.sender; assetsById[nextAssetId].issuer = msg.sender; assetsById[nextAssetId].content = content; assetsById[nextAssetId].sellPrice = sellPrice; assetsById[nextAssetId].status = assetStatus.Released; // Update lastAssetId lastAssetId++; // Event log IssueAsset(nextAssetId, msg.sender, sellPrice); return nextAssetId; } // Issuer sends a new free asset to a given user as a gift function issueAssetTo(string content, address to) returns (bool) { uint256 assetId = issueAsset(content, 0); // 0 tokens, as a gift if (assetId == 0) { Error('issueAssetTo: asset has not been properly issued'); return (false); } // The brand new asset is inmediatly sent to the recipient return(sendAssetTo(assetId, to)); } // Seller can block tradability of its assets function setAssetUnfungible(uint256 assetId) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('setAssetUnfungible: assetId must not be zero'); return false; } // Check whether the asset belongs to the caller if (assetsById[assetId].assetOwner != msg.sender) { Error('setAssetUnfungible: only owners of the asset are allowed to update its status'); return false; } assetsById[assetId].status = assetStatus.Unfungible; // Event log SetAssetUnfungible(assetId, msg.sender); return true; } // Seller updates the price of its assets and its status to ForSale function setAssetPrice(uint256 assetId, uint256 sellPrice) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('setAssetPrice: assetId must not be zero'); return false; } // Check whether the asset belongs to the caller if (assetsById[assetId].assetOwner != msg.sender) { Error('setAssetPrice: only owners of the asset are allowed to set its price and update its status'); return false; } assetsById[assetId].sellPrice = sellPrice; assetsById[assetId].status = assetStatus.ForSale; // Event log SetAssetPrice(assetId, msg.sender, sellPrice); return true; } // Owner updates the fees for assets sale transactions function setAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade) returns (bool) { // Check this is called by owner if (!isOwner()) { Error('setAssetSaleFees: only Owner is authorized to update asset sale fees.'); return false; } // Check new fees are consistent if (feeIssuer + feeWorldTrade > 1000) { Error('setAssetSaleFees: added fees exceed 100.0%. Not updated.'); return false; } assetFeeIssuer = feeIssuer; assetFeeWorldTrade = feeWorldTrade; // Event log SetAssetSaleFees(feeIssuer, feeWorldTrade); return true; } // **** EVENTS // Triggered when a seller sends its asset to a buyer and receives the corresponding tokens event SendAssetTo(uint256 assetId, address assetBuyer); // Triggered when a buyer sends its tokens to a seller and receives the specified asset event BuyAsset(uint256 assetId, uint256 amount); // Triggered when the admin issues a new asset event IssueAsset(uint256 nextAssetId, address assetOwner, uint256 sellPrice); // Triggered when the user updates its asset status to Unfungible event SetAssetUnfungible(uint256 assetId, address assetOwner); // Triggered when the user updates its asset price and status to ForSale event SetAssetPrice(uint256 assetId, address assetOwner, uint256 sellPrice); // Triggered when the owner updates the asset sale fees event SetAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade); }
Owner updates the fees for assets sale transactions Check this is called by owner
function setAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade) returns (bool) { if (!isOwner()) { Error('setAssetSaleFees: only Owner is authorized to update asset sale fees.'); return false; } if (feeIssuer + feeWorldTrade > 1000) { Error('setAssetSaleFees: added fees exceed 100.0%. Not updated.'); return false; } assetFeeIssuer = feeIssuer; assetFeeWorldTrade = feeWorldTrade; return true; SetAssetSaleFees(feeIssuer, feeWorldTrade); }
2,487,315
// basic multisig wallet with spending limits, token types and other controls built in // wondering if I should build in a master lock which enables free spend after a certain time? pragma solidity ^0.4.24; /** * @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) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract MultiSig { address constant internal CONTRACT_SIGNATURE1 = 0xa5a5f62BfA22b1E42A98Ce00131eA658D5E29B37; // SB address constant internal CONTRACT_SIGNATURE2 = 0x9115a6162D6bC3663dC7f4Ea46ad87db6B9CB926; // SM mapping(address => uint256) internal mSignatures; mapping(address => uint256) internal mLastSpend; // gas limit uint256 public GAS_PRICE_LIMIT = 200 * 10**9; // Gas limit 200 gwei // live parameters uint256 public constant WHOLE_ETHER = 10**18; uint256 public constant FRACTION_ETHER = 10**14; uint256 public constant COSIGN_MAX_TIME= 900; // maximum delay between signatures uint256 public constant DAY_LENGTH = 300; // length of day in seconds // ether spending uint256 public constant MAX_DAILY_SOLO_SPEND = (5*WHOLE_ETHER); // amount which can be withdrawn without co-signing uint256 public constant MAX_DAILY_COSIGN_SEND = (500*WHOLE_ETHER); // token spending uint256 public constant MAX_DAILY_TOKEN_SOLO_SPEND = 2500000*WHOLE_ETHER; // ~5 eth uint256 public constant MAX_DAILY_TOKEN_COSIGN_SPEND = 250000000*WHOLE_ETHER; // ~500 eth uint256 internal mAmount1=0; uint256 internal mAmount2=0; // set the time of a signature function sendsignature() internal { // check if these signatures are authorised require((msg.sender == CONTRACT_SIGNATURE1 || msg.sender == CONTRACT_SIGNATURE2));//, "Only signatories can sign"); // assign signature uint256 timestamp = block.timestamp; mSignatures[msg.sender] = timestamp; } // inserted for paranoia but may need to change gas prices in future function SetGasLimit(uint256 newGasLimit) public { require((msg.sender == CONTRACT_SIGNATURE1 || msg.sender == CONTRACT_SIGNATURE2));//, "Only signatories can call"); GAS_PRICE_LIMIT = newGasLimit; // Gas limit default 200 gwei } // implicitly calls spend - if both signatures have signed we then spend function spendlarge(uint256 _to, uint256 _main, uint256 _fraction) public returns (bool valid) { require( _to != 0x0);//, "Must send to valid address"); require( _main<= MAX_DAILY_COSIGN_SEND);//, "Cannot spend more than 500 eth"); require( _fraction< (WHOLE_ETHER/FRACTION_ETHER));//, "Fraction must be less than 10000"); require (tx.gasprice <= GAS_PRICE_LIMIT);//, "tx.gasprice exceeds limit"); // usually called after sign but will work if top level function is called by both parties sendsignature(); uint256 currentTime = block.timestamp; uint256 valid1=0; uint256 valid2=0; // check both signatures have been logged within the time frame // one of these times will obviously be zero if (block.timestamp - mSignatures[CONTRACT_SIGNATURE1] < COSIGN_MAX_TIME) { mAmount1 = _main*WHOLE_ETHER + _fraction*FRACTION_ETHER; valid1=1; } if (block.timestamp - mSignatures[CONTRACT_SIGNATURE2] < COSIGN_MAX_TIME) { mAmount2 = _main*WHOLE_ETHER + _fraction*FRACTION_ETHER; valid2=1; } if (valid1==1 && valid2==1) //"Both signatures must sign"); { // if this was called in less than 24 hours then don't allow spend require( (currentTime - mLastSpend[msg.sender]) > DAY_LENGTH);//, "You can't call this more than once per day per signature"); if (mAmount1 == mAmount2) { // transfer eth to the destination address(_to).transfer(mAmount1); // clear the state valid1=0; valid2=0; mAmount1=0; mAmount2=0; // clear the signature timestamps endsigning(); return true; } } // out of time or need another signature return false; } // used for individual wallet holders to take a small amount of ether function takedaily(address _to) public returns (bool valid) { require( _to != 0x0);//, "Must send to valid address"); require (tx.gasprice <= GAS_PRICE_LIMIT);//, "tx.gasprice exceeds limit"); // check if these signatures are authorised require((msg.sender == CONTRACT_SIGNATURE1 || msg.sender == CONTRACT_SIGNATURE2));//, "Only signatories can sign"); uint256 currentTime = block.timestamp; // if this was called in less than 24 hours then don't allow spend require(currentTime - mLastSpend[msg.sender] > DAY_LENGTH);//, "You can't call this more than once per day per signature"); // transfer eth to the destination _to.transfer(MAX_DAILY_SOLO_SPEND); mLastSpend[msg.sender] = currentTime; return true; } // implicitly calls spend - if both signatures have signed we then spend function spendtokens(ERC20Basic contractaddress, uint256 _to, uint256 _main, uint256 _fraction) public returns (bool valid) { require( _to != 0x0);//, "Must send to valid address"); require(_main <= MAX_DAILY_TOKEN_COSIGN_SPEND);// , "Cannot spend more than 150000000 per day"); require(_fraction< (WHOLE_ETHER/FRACTION_ETHER));//, "Fraction must be less than 10000"); // usually called after sign but will work if top level function is called by both parties sendsignature(); uint256 currentTime = block.timestamp; uint256 valid1=0; uint256 valid2=0; // check both signatures have been logged within the time frame // one of these times will obviously be zero if (block.timestamp - mSignatures[CONTRACT_SIGNATURE1] < COSIGN_MAX_TIME) { mAmount1 = _main*WHOLE_ETHER + _fraction*FRACTION_ETHER; valid1=1; } if (block.timestamp - mSignatures[CONTRACT_SIGNATURE2] < COSIGN_MAX_TIME) { mAmount2 = _main*WHOLE_ETHER + _fraction*FRACTION_ETHER; valid2=1; } if (valid1==1 && valid2==1) //"Both signatures must sign"); { // if this was called in less than 24 hours then don't allow spend require(currentTime - mLastSpend[msg.sender] > DAY_LENGTH);//, "You can't call this more than once per day per signature"); if (mAmount1 == mAmount2) { uint256 valuetosend = _main*WHOLE_ETHER + _fraction*FRACTION_ETHER; // transfer eth to the destination contractaddress.transfer(address(_to), valuetosend); // clear the state valid1=0; valid2=0; mAmount1=0; mAmount2=0; // clear the signature timestamps endsigning(); return true; } } // out of time or need another signature return false; } // used to take a small amount of daily tokens function taketokendaily(ERC20Basic contractaddress, uint256 _to) public returns (bool valid) { require( _to != 0x0);//, "Must send to valid address"); // check if these signatures are authorised require((msg.sender == CONTRACT_SIGNATURE1 || msg.sender == CONTRACT_SIGNATURE2));//, "Only signatories can sign"); uint256 currentTime = block.timestamp; // if this was called in less than 24 hours then don't allow spend require(currentTime - mLastSpend[msg.sender] > DAY_LENGTH);//, "You can't call this more than once per day per signature"); // transfer eth to the destination contractaddress.transfer(address(_to), MAX_DAILY_TOKEN_SOLO_SPEND); mLastSpend[msg.sender] = currentTime; return true; } function endsigning() internal { // only called when spending was successful - sets the timestamp of last call mLastSpend[CONTRACT_SIGNATURE1]=block.timestamp; mLastSpend[CONTRACT_SIGNATURE2]=block.timestamp; mSignatures[CONTRACT_SIGNATURE1]=0; mSignatures[CONTRACT_SIGNATURE2]=0; } function () public payable { } }
used for individual wallet holders to take a small amount of ether check if these signatures are authorised if this was called in less than 24 hours then don't allow spend transfer eth to the destination
function takedaily(address _to) public returns (bool valid) { uint256 currentTime = block.timestamp; _to.transfer(MAX_DAILY_SOLO_SPEND); mLastSpend[msg.sender] = currentTime; return true; }
14,532,304
/* Copyright 2018 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; pragma experimental "v0.5.0"; import { WETH9 } from "canonical-weth/contracts/WETH9.sol"; import { BucketLender } from "./BucketLender.sol"; import { AdvancedTokenInteract } from "../../../lib/AdvancedTokenInteract.sol"; import { TokenInteract } from "../../../lib/TokenInteract.sol"; /** * @title BucketLenderProxy * @author dYdX * * TokenProxy for BucketLender contracts */ contract BucketLenderProxy { using TokenInteract for address; using AdvancedTokenInteract for address; // ============ Constants ============ // Address of the WETH token address public WETH; // ============ Constructor ============ constructor( address weth ) public { WETH = weth; } // ============ Public Functions ============ /** * Fallback function. Disallows ETH to be sent to this contract without data except when * unwrapping WETH. */ function () external payable { require( // coverage-disable-line msg.sender == WETH, "BucketLenderProxy#fallback: Cannot recieve ETH directly unless unwrapping WETH" ); } /** * Send ETH directly to this contract, convert it to WETH, and sent it to a BucketLender * * @param bucketLender The address of the BucketLender contract to deposit into * @return The bucket number that was deposited into */ function depositEth( address bucketLender ) external payable returns (uint256) { address weth = WETH; require( weth == BucketLender(bucketLender).OWED_TOKEN(), "BucketLenderProxy#depositEth: BucketLender does not take WETH" ); WETH9(weth).deposit.value(msg.value)(); return depositInternal( bucketLender, weth, msg.value ); } /** * Deposits tokens from msg.sender into a BucketLender * * @param bucketLender The address of the BucketLender contract to deposit into * @param amount The amount of token to deposit * @return The bucket number that was deposited into */ function deposit( address bucketLender, uint256 amount ) external returns (uint256) { address token = BucketLender(bucketLender).OWED_TOKEN(); token.transferFrom(msg.sender, address(this), amount); return depositInternal( bucketLender, token, amount ); } /** * Withdraw tokens from a BucketLender * * @param bucketLender The address of the BucketLender contract to withdraw from * @param buckets The buckets to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket * @return Values corresponding to: * [0] = The number of owedTokens withdrawn * [1] = The number of heldTokens withdrawn */ function withdraw( address bucketLender, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256) { address owedToken = BucketLender(bucketLender).OWED_TOKEN(); address heldToken = BucketLender(bucketLender).HELD_TOKEN(); ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(bucketLender).withdraw( buckets, maxWeights, msg.sender ); transferInternal(owedToken, msg.sender, owedTokenAmount); transferInternal(heldToken, msg.sender, heldTokenAmount); return (owedTokenAmount, heldTokenAmount); } /** * Reinvest tokens by withdrawing them from one BucketLender and depositing them into another * * @param withdrawFrom The address of the BucketLender contract to withdraw from * @param depositInto The address of the BucketLender contract to deposit into * @param buckets The buckets to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket * @return Values corresponding to: * [0] = The bucket number that was deposited into * [1] = The number of owedTokens reinvested * [2] = The number of heldTokens withdrawn */ function rollover( address withdrawFrom, address depositInto, uint256[] buckets, uint256[] maxWeights ) external returns (uint256, uint256, uint256) { address owedToken = BucketLender(depositInto).OWED_TOKEN(); // the owedTokens of the two BucketLenders must be the same require ( owedToken == BucketLender(withdrawFrom).OWED_TOKEN(), "BucketLenderTokenProxy#rollover: Token mismatch" ); // withdraw from the first BucketLender ( uint256 owedTokenAmount, uint256 heldTokenAmount ) = BucketLender(withdrawFrom).withdraw( buckets, maxWeights, msg.sender ); // reinvest any owedToken into the second BucketLender uint256 bucket = depositInternal( depositInto, owedToken, owedTokenAmount ); // return any heldToken to the msg.sender address heldToken = BucketLender(withdrawFrom).HELD_TOKEN(); transferInternal(heldToken, msg.sender, heldTokenAmount); return (bucket, owedTokenAmount, heldTokenAmount); } // ============ Private Functions ============ function depositInternal( address bucketLender, address token, uint256 amount ) private returns (uint256) { token.ensureAllowance(bucketLender, amount); return BucketLender(bucketLender).deposit(msg.sender, amount); } function transferInternal( address token, address recipient, uint256 amount ) private { address weth = WETH; if (token == weth) { if (amount != 0) { WETH9(weth).withdraw(amount); msg.sender.transfer(amount); } } else { token.transfer(recipient, amount); } } }
Fallback function. Disallows ETH to be sent to this contract without data except when unwrapping WETH./
function () external payable { msg.sender == WETH, "BucketLenderProxy#fallback: Cannot recieve ETH directly unless unwrapping WETH" ); }
1,081,281
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { GovernanceVaultUpgrade } from "../vault/GovernanceVaultUpgrade.sol"; import { GasCompensator } from "./GasCompensator.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @notice This contract should upgrade governance to be able to compensate gas for certain actions. * These actions are set to castVote, castDelegatedVote in this contract. * */ contract GovernanceGasUpgrade is GovernanceVaultUpgrade, GasCompensator { /** * @notice constructor * @param _gasCompLogic gas compensation vault address * @param _userVault tornado vault address * */ constructor(address _gasCompLogic, address _userVault) public GovernanceVaultUpgrade(_userVault) GasCompensator(_gasCompLogic) {} /// @notice check that msg.sender is multisig modifier onlyMultisig() { require(msg.sender == returnMultisigAddress(), "only multisig"); _; } /** * @notice receive ether function, does nothing but receive ether * */ receive() external payable {} /** * @notice function to add a certain amount of ether for gas compensations * @dev send ether is used in the logic as we don't expect multisig to make a reentrancy attack on governance * @param gasCompensationsLimit the amount of gas to be compensated * */ function setGasCompensations(uint256 gasCompensationsLimit) external virtual override onlyMultisig { require(payable(address(gasCompensationVault)).send(Math.min(gasCompensationsLimit, address(this).balance))); } /** * @notice function to withdraw funds from the gas compensator * @dev send ether is used in the logic as we don't expect multisig to make a reentrancy attack on governance * @param amount the amount of ether to withdraw * */ function withdrawFromHelper(uint256 amount) external virtual override onlyMultisig { gasCompensationVault.withdrawToGovernance(amount); } /** * @notice function to cast callers votes on a proposal * @dev IMPORTANT: This function uses the gasCompensation modifier. * as such this function can trigger a payable fallback. It is not possible to vote without revert more than once, without hasAccountVoted being true, eliminating gas refunds in this case. Gas compensation is also using the low level send(), forwarding 23000 gas as to disallow further logic execution above that threshold. * @param proposalId id of proposal account is voting on * @param support true if yes false if no * */ function castVote(uint256 proposalId, bool support) external virtual override gasCompensation( msg.sender, !hasAccountVoted(proposalId, msg.sender) && !checkIfQuorumReached(proposalId), (msg.sender == tx.origin ? 21e3 : 0) ) { _castVote(msg.sender, proposalId, support); } /** * @notice function to cast callers votes and votes delegated to the caller * @param from array of addresses that should have delegated to voter * @param proposalId id of proposal account is voting on * @param support true if yes false if no * */ function castDelegatedVote( address[] memory from, uint256 proposalId, bool support ) external virtual override { require(from.length > 0, "Can not be empty"); _castDelegatedVote(from, proposalId, support, !hasAccountVoted(proposalId, msg.sender) && !checkIfQuorumReached(proposalId)); } /// @notice checker for success on deployment /// @return returns precise version of governance function version() external pure virtual override returns (string memory) { return "2.lottery-and-gas-upgrade"; } /** * @notice function to check if quorum has been reached on a given proposal * @param proposalId id of proposal * @return true if quorum has been reached * */ function checkIfQuorumReached(uint256 proposalId) public view returns (bool) { return (proposals[proposalId].forVotes + proposals[proposalId].againstVotes >= QUORUM_VOTES); } /** * @notice function to check if account has voted on a proposal * @param proposalId id of proposal account should have voted on * @param account address of the account * @return true if acc has voted * */ function hasAccountVoted(uint256 proposalId, address account) public view returns (bool) { return proposals[proposalId].receipts[account].hasVoted; } /** * @notice function to retrieve the multisig address * @dev reasoning: if multisig changes we need governance to approve the next multisig address, * so simply inherit in a governance upgrade from this function and set the new address * @return the multisig address * */ function returnMultisigAddress() public pure virtual returns (address) { return 0xb04E030140b30C27bcdfaafFFA98C57d80eDa7B4; } /** * @notice This should handle the logic of the external function * @dev IMPORTANT: This function uses the gasCompensation modifier. * as such this function can trigger a payable fallback. * It is not possible to vote without revert more than once, * without hasAccountVoted being true, eliminating gas refunds in this case. * Gas compensation is also using the low level send(), forwarding 23000 gas * as to disallow further logic execution above that threshold. * @param from array of addresses that should have delegated to voter * @param proposalId id of proposal account is voting on * @param support true if yes false if no * @param gasCompensated true if gas should be compensated (given all internal checks pass) * */ function _castDelegatedVote( address[] memory from, uint256 proposalId, bool support, bool gasCompensated ) internal gasCompensation(msg.sender, gasCompensated, (msg.sender == tx.origin ? 21e3 : 0)) { for (uint256 i = 0; i < from.length; i++) { address delegator = from[i]; require(delegatedTo[delegator] == msg.sender || delegator == msg.sender, "Governance: not authorized"); require(!gasCompensated || !hasAccountVoted(proposalId, delegator), "Governance: voted already"); _castVote(delegator, proposalId, support); } } }
function to check if account has voted on a proposal proposalId id of proposal account should have voted on account address of the account return true if acc has voted /
function hasAccountVoted(uint256 proposalId, address account) public view returns (bool) { return proposals[proposalId].receipts[account].hasVoted; }
1,075,314
pragma solidity 0.4.24; pragma experimental ABIEncoderV2; contract IERC20Token { // solhint-disable 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 ); /// @dev 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 True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev 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 True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `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 wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @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) external view returns (uint256); } contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require( c / a == b, "UINT256_OVERFLOW" ); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require( b <= a, "UINT256_UNDERFLOW" ); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require( c >= a, "UINT256_OVERFLOW" ); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint256) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibMath is SafeMath { /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorFloor( numerator, denominator, target ), "ROUNDING_ERROR" ); partialAmount = safeDiv( safeMul(numerator, target), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorCeil( numerator, denominator, target ), "ROUNDING_ERROR" ); // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = safeDiv( safeAdd( safeMul(numerator, target), safeSub(denominator, 1) ), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); partialAmount = safeDiv( safeMul(numerator, target), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = safeDiv( safeAdd( safeMul(numerator, target), safeSub(denominator, 1) ), denominator ); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = safeMul(1000, remainder) >= safeMul(numerator, target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = safeSub(denominator, remainder) % denominator; isError = safeMul(1000, remainder) >= safeMul(numerator, target); return isError; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to < b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to < b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require( b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require( b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength( bytes memory b, uint256 index ) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require( b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes( bytes memory dest, bytes memory source ) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require( dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED" ); memCopy( dest.contentAddress(), source.contentAddress(), sourceLen ); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibEIP712 { // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "0x Protocol"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "2"; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; constructor () public { EIP712_DOMAIN_HASH = keccak256(abi.encodePacked( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), bytes32(address(this)) )); } /// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to this EIP712 Domain. function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 eip712DomainHash = EIP712_DOMAIN_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibOrder is LibEIP712 { // Hash for the EIP712 Order Schema bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256(abi.encodePacked( "Order(", "address makerAddress,", "address takerAddress,", "address feeRecipientAddress,", "address senderAddress,", "uint256 makerAssetAmount,", "uint256 takerAssetAmount,", "uint256 makerFee,", "uint256 takerFee,", "uint256 expirationTimeSeconds,", "uint256 salt,", "bytes makerAssetData,", "bytes takerAssetData", ")" )); // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's state is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted. uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy. } // solhint-enable max-line-length struct OrderInfo { uint8 orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 hash of the order (see LibOrder.getOrderHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates Keccak-256 hash of the order. /// @param order The order structure. /// @return Keccak-256 EIP712 hash of the order. function getOrderHash(Order memory order) internal view returns (bytes32 orderHash) { orderHash = hashEIP712Message(hashOrder(order)); return orderHash; } /// @dev Calculates EIP712 hash of the order. /// @param order The order structure. /// @return EIP712 hash of the order. function hashOrder(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH; bytes32 makerAssetDataHash = keccak256(order.makerAssetData); bytes32 takerAssetDataHash = keccak256(order.takerAssetData); // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // bytes32(order.makerAddress), // bytes32(order.takerAddress), // bytes32(order.feeRecipientAddress), // bytes32(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData) // )); assembly { // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) // Hash in place mstore(pos1, schemaHash) mstore(pos2, makerAssetDataHash) mstore(pos3, takerAssetDataHash) result := keccak256(pos1, 416) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) } return result; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibFillResults is SafeMath { struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s). } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 leftMakerAssetSpreadAmount; // Spread between price of left and right order, denominated in the left order's makerAsset, paid to taker. } /// @dev Adds properties of both FillResults instances. /// Modifies the first FillResults instance specified. /// @param totalFillResults Fill results instance that will be added onto. /// @param singleFillResults Fill results instance that will be added to totalFillResults. function addFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults) internal pure { totalFillResults.makerAssetFilledAmount = safeAdd(totalFillResults.makerAssetFilledAmount, singleFillResults.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = safeAdd(totalFillResults.takerAssetFilledAmount, singleFillResults.takerAssetFilledAmount); totalFillResults.makerFeePaid = safeAdd(totalFillResults.makerFeePaid, singleFillResults.makerFeePaid); totalFillResults.takerFeePaid = safeAdd(totalFillResults.takerFeePaid, singleFillResults.takerFeePaid); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IExchangeCore { /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IMatchOrders { /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public returns (LibFillResults.MatchedFillResults memory matchedFillResults); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract ISignatureValidator { /// @dev Approves a hash on-chain using any valid signature type. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof that the hash has been signed by signer. function preSign( bytes32 hash, address signerAddress, bytes signature ) external; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external; /// @dev Verifies that a signature is valid. /// @param hash Message hash that is signed. /// @param signerAddress Address of signer. /// @param signature Proof of signing. /// @return Validity of order signature. function isValidSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract ITransactions { /// @dev Executes an exchange method call in the context of signer. /// @param salt Arbitrary number to ensure uniqueness of transaction hash. /// @param signerAddress Address of transaction signer. /// @param data AbiV2 encoded calldata. /// @param signature Proof of signer transaction by signer. function executeTransaction( uint256 salt, address signerAddress, bytes data, bytes signature ) external; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IAssetProxyDispatcher { /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order LibOrder.Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (LibFillResults.FillResults memory fillResults); /// @dev Fills an order with specified parameters and ECDSA signature. /// Returns false if the transaction would otherwise revert. /// @param order LibOrder.Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (LibFillResults.FillResults memory fillResults); /// @dev Synchronously executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrKill. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Fills an order with specified parameters and ECDSA signature. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrders( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrders( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public; /// @dev Fetches information for all passed in orders /// @param orders Array of order specifications. /// @return Array of OrderInfo instances that correspond to each order. function getOrdersInfo(LibOrder.Order[] memory orders) public view returns (LibOrder.OrderInfo[] memory); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // solhint-disable no-empty-blocks contract IExchange is IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, IWrapperFunctions {} /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibConstants { using LibBytes for bytes; bytes4 constant internal ERC20_DATA_ID = bytes4(keccak256("ERC20Token(address)")); bytes4 constant internal ERC721_DATA_ID = bytes4(keccak256("ERC721Token(address,uint256)")); uint256 constant internal MAX_UINT = 2**256 - 1; uint256 constant internal PERCENTAGE_DENOMINATOR = 10**18; uint256 constant internal MAX_FEE_PERCENTAGE = 5 * PERCENTAGE_DENOMINATOR / 100; // 5% uint256 constant internal MAX_WETH_FILL_PERCENTAGE = 95 * PERCENTAGE_DENOMINATOR / 100; // 95% // solhint-disable var-name-mixedcase IExchange internal EXCHANGE; IEtherToken internal ETHER_TOKEN; IERC20Token internal ZRX_TOKEN; bytes internal ZRX_ASSET_DATA; bytes internal WETH_ASSET_DATA; // solhint-enable var-name-mixedcase constructor ( address _exchange, bytes memory _zrxAssetData, bytes memory _wethAssetData ) public { EXCHANGE = IExchange(_exchange); ZRX_ASSET_DATA = _zrxAssetData; WETH_ASSET_DATA = _wethAssetData; address etherToken = _wethAssetData.readAddress(16); address zrxToken = _zrxAssetData.readAddress(16); ETHER_TOKEN = IEtherToken(etherToken); ZRX_TOKEN = IERC20Token(zrxToken); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MWeth { /// @dev Converts message call's ETH value into WETH. function convertEthToWeth() internal; /// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient. /// Refunds any excess ETH to msg.sender. /// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders. /// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. function transferEthFeeAndRefund( uint256 wethSoldExcludingFeeOrders, uint256 wethSoldForZrx, uint256 feePercentage, address feeRecipient ) internal; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinWeth is LibMath, LibConstants, MWeth { /// @dev Default payabale function, this allows us to withdraw WETH function () public payable { require( msg.sender == address(ETHER_TOKEN), "DEFAULT_FUNCTION_WETH_CONTRACT_ONLY" ); } /// @dev Converts message call's ETH value into WETH. function convertEthToWeth() internal { require( msg.value > 0, "INVALID_MSG_VALUE" ); ETHER_TOKEN.deposit.value(msg.value)(); } /// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient. /// Refunds any excess ETH to msg.sender. /// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders. /// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. function transferEthFeeAndRefund( uint256 wethSoldExcludingFeeOrders, uint256 wethSoldForZrx, uint256 feePercentage, address feeRecipient ) internal { // Ensure feePercentage is less than 5%. require( feePercentage <= MAX_FEE_PERCENTAGE, "FEE_PERCENTAGE_TOO_LARGE" ); // Ensure that no extra WETH owned by this contract has been sold. uint256 wethSold = safeAdd(wethSoldExcludingFeeOrders, wethSoldForZrx); require( wethSold <= msg.value, "OVERSOLD_WETH" ); // Calculate amount of WETH that hasn't been sold. uint256 wethRemaining = safeSub(msg.value, wethSold); // Calculate ETH fee to pay to feeRecipient. uint256 ethFee = getPartialAmountFloor( feePercentage, PERCENTAGE_DENOMINATOR, wethSoldExcludingFeeOrders ); // Ensure fee is less than amount of WETH remaining. require( ethFee <= wethRemaining, "INSUFFICIENT_ETH_REMAINING" ); // Do nothing if no WETH remaining if (wethRemaining > 0) { // Convert remaining WETH to ETH ETHER_TOKEN.withdraw(wethRemaining); // Pay ETH to feeRecipient if (ethFee > 0) { feeRecipient.transfer(ethFee); } // Refund remaining ETH to msg.sender. uint256 ethRefund = safeSub(wethRemaining, ethFee); if (ethRefund > 0) { msg.sender.transfer(ethRefund); } } } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IAssets { /// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to /// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be /// used to withdraw assets that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of ERC20 token to withdraw. function withdrawAsset( bytes assetData, uint256 amount ) external; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MAssets is IAssets { /// @dev Transfers given amount of asset to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferAssetToSender( bytes memory assetData, uint256 amount ) internal; /// @dev Decodes ERC20 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC20Token( bytes memory assetData, uint256 amount ) internal; /// @dev Decodes ERC721 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC721Token( bytes memory assetData, uint256 amount ) internal; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MExchangeWrapper { /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellWeth( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyExactAmountWithWeth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) internal returns (LibFillResults.FillResults memory totalFillResults); /// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee /// that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues). /// It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX /// as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. /// @param zrxBuyAmount Desired amount of ZRX to buy. /// @param signatures Proofs that orders have been created by makers. /// @return totalFillResults Amounts filled and fees paid by maker and taker. function marketBuyExactZrxWithWeth( LibOrder.Order[] memory orders, uint256 zrxBuyAmount, bytes[] memory signatures ) internal returns (LibFillResults.FillResults memory totalFillResults); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IForwarderCore { /// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketSellOrdersWithEth( LibOrder.Order[] memory orders, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( LibFillResults.FillResults memory orderFillResults, LibFillResults.FillResults memory feeOrderFillResults ); /// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param makerAssetFillAmount Desired amount of makerAsset to purchase. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketBuyOrdersWithEth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( LibFillResults.FillResults memory orderFillResults, LibFillResults.FillResults memory feeOrderFillResults ); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinForwarderCore is LibFillResults, LibMath, LibConstants, MWeth, MAssets, MExchangeWrapper, IForwarderCore { using LibBytes for bytes; /// @dev Constructor approves ERC20 proxy to transfer ZRX and WETH on this contract's behalf. constructor () public { address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID); require( proxyAddress != address(0), "UNREGISTERED_ASSET_PROXY" ); ETHER_TOKEN.approve(proxyAddress, MAX_UINT); ZRX_TOKEN.approve(proxyAddress, MAX_UINT); } /// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketSellOrdersWithEth( LibOrder.Order[] memory orders, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { // Convert ETH to WETH. convertEthToWeth(); uint256 wethSellAmount; uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { // Calculate amount of WETH that won't be spent on ETH fees. wethSellAmount = getPartialAmountFloor( PERCENTAGE_DENOMINATOR, safeAdd(PERCENTAGE_DENOMINATOR, feePercentage), msg.value ); // Market sell available WETH. // ZRX fees are paid with this contract's balance. orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); // The fee amount must be deducted from the amount transfered back to sender. makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); } else { // 5% of WETH is reserved for filling feeOrders and paying feeRecipient. wethSellAmount = getPartialAmountFloor( MAX_WETH_FILL_PERCENTAGE, PERCENTAGE_DENOMINATOR, msg.value ); // Market sell 95% of WETH. // ZRX fees are payed with this contract's balance. orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); // Buy back all ZRX spent on fees. zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } // Transfer feePercentage of total ETH spent on primary orders to feeRecipient. // Refund remaining ETH to msg.sender. transferEthFeeAndRefund( orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); // Transfer purchased assets to msg.sender. transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased); } /// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param makerAssetFillAmount Desired amount of makerAsset to purchase. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketBuyOrdersWithEth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { // Convert ETH to WETH. convertEthToWeth(); uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { // If the makerAsset is ZRX, it is not necessary to pay fees out of this // contracts's ZRX balance because fees are factored into the price of the order. orderFillResults = marketBuyExactZrxWithWeth( orders, makerAssetFillAmount, signatures ); // The fee amount must be deducted from the amount transfered back to sender. makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); } else { // Attemp to purchase desired amount of makerAsset. // ZRX fees are payed with this contract's balance. orderFillResults = marketBuyExactAmountWithWeth( orders, makerAssetFillAmount, signatures ); // Buy back all ZRX spent on fees. zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } // Transfer feePercentage of total ETH spent on primary orders to feeRecipient. // Refund remaining ETH to msg.sender. transferEthFeeAndRefund( orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); // Transfer purchased assets to msg.sender. transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased); } } contract IOwnable { function transferOwnership(address newOwner) public; } contract Ownable is IOwnable { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner() { require( msg.sender == owner, "ONLY_CONTRACT_OWNER" ); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC721Token { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// perator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) public view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinAssets is Ownable, LibConstants, MAssets { using LibBytes for bytes; bytes4 constant internal ERC20_TRANSFER_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); /// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to /// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be /// used to withdraw assets that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of ERC20 token to withdraw. function withdrawAsset( bytes assetData, uint256 amount ) external onlyOwner { transferAssetToSender(assetData, amount); } /// @dev Transfers given amount of asset to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferAssetToSender( bytes memory assetData, uint256 amount ) internal { bytes4 proxyId = assetData.readBytes4(0); if (proxyId == ERC20_DATA_ID) { transferERC20Token(assetData, amount); } else if (proxyId == ERC721_DATA_ID) { transferERC721Token(assetData, amount); } else { revert("UNSUPPORTED_ASSET_PROXY"); } } /// @dev Decodes ERC20 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC20Token( bytes memory assetData, uint256 amount ) internal { address token = assetData.readAddress(16); // Transfer tokens. // We do a raw call so we can check the success separate // from the return data. bool success = token.call(abi.encodeWithSelector( ERC20_TRANSFER_SELECTOR, msg.sender, amount )); require( success, "TRANSFER_FAILED" ); // Check return data. // If there is no return data, we assume the token incorrectly // does not return a bool. In this case we expect it to revert // on failure, which was handled above. // If the token does return data, we require that it is a single // value that evaluates to true. assembly { if returndatasize { success := 0 if eq(returndatasize, 32) { // First 64 bytes of memory are reserved scratch space returndatacopy(0, 0, 32) success := mload(0) } } } require( success, "TRANSFER_FAILED" ); } /// @dev Decodes ERC721 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC721Token( bytes memory assetData, uint256 amount ) internal { require( amount == 1, "INVALID_AMOUNT" ); // Decode asset data. address token = assetData.readAddress(16); uint256 tokenId = assetData.readUint256(36); // Perform transfer. IERC721Token(token).transferFrom( address(this), msg.sender, tokenId ); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibAbiEncoder { /// @dev ABI encodes calldata for `fillOrder`. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return ABI encoded calldata for `fillOrder`. function abiEncodeFillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal pure returns (bytes memory fillOrderCalldata) { // We need to call MExchangeCore.fillOrder using a delegatecall in // assembly so that we can intercept a call that throws. For this, we // need the input encoded in memory in the Ethereum ABIv2 format [1]. // | Area | Offset | Length | Contents | // | -------- |--------|---------|-------------------------------------------- | // | Header | 0x00 | 4 | function selector | // | Params | | 3 * 32 | function parameters: | // | | 0x00 | | 1. offset to order (*) | // | | 0x20 | | 2. takerAssetFillAmount | // | | 0x40 | | 3. offset to signature (*) | // | Data | | 12 * 32 | order: | // | | 0x000 | | 1. senderAddress | // | | 0x020 | | 2. makerAddress | // | | 0x040 | | 3. takerAddress | // | | 0x060 | | 4. feeRecipientAddress | // | | 0x080 | | 5. makerAssetAmount | // | | 0x0A0 | | 6. takerAssetAmount | // | | 0x0C0 | | 7. makerFeeAmount | // | | 0x0E0 | | 8. takerFeeAmount | // | | 0x100 | | 9. expirationTimeSeconds | // | | 0x120 | | 10. salt | // | | 0x140 | | 11. Offset to makerAssetData (*) | // | | 0x160 | | 12. Offset to takerAssetData (*) | // | | 0x180 | 32 | makerAssetData Length | // | | 0x1A0 | ** | makerAssetData Contents | // | | 0x1C0 | 32 | takerAssetData Length | // | | 0x1E0 | ** | takerAssetData Contents | // | | 0x200 | 32 | signature Length | // | | 0x220 | ** | signature Contents | // * Offsets are calculated from the beginning of the current area: Header, Params, Data: // An offset stored in the Params area is calculated from the beginning of the Params section. // An offset stored in the Data area is calculated from the beginning of the Data section. // ** The length of dynamic array contents are stored in the field immediately preceeding the contents. // [1]: https://solidity.readthedocs.io/en/develop/abi-spec.html assembly { // Areas below may use the following variables: // 1. <area>Start -- Start of this area in memory // 2. <area>End -- End of this area in memory. This value may // be precomputed (before writing contents), // or it may be computed as contents are written. // 3. <area>Offset -- Current offset into area. If an area's End // is precomputed, this variable tracks the // offsets of contents as they are written. /////// Setup Header Area /////// // Load free memory pointer fillOrderCalldata := mload(0x40) // bytes4(keccak256("fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)")) // = 0xb4be83d5 // Leave 0x20 bytes to store the length mstore(add(fillOrderCalldata, 0x20), 0xb4be83d500000000000000000000000000000000000000000000000000000000) let headerAreaEnd := add(fillOrderCalldata, 0x24) /////// Setup Params Area /////// // This area is preallocated and written to later. // This is because we need to fill in offsets that have not yet been calculated. let paramsAreaStart := headerAreaEnd let paramsAreaEnd := add(paramsAreaStart, 0x60) let paramsAreaOffset := paramsAreaStart /////// Setup Data Area /////// let dataAreaStart := paramsAreaEnd let dataAreaEnd := dataAreaStart // Offset from the source data we're reading from let sourceOffset := order // arrayLenBytes and arrayLenWords track the length of a dynamically-allocated bytes array. let arrayLenBytes := 0 let arrayLenWords := 0 /////// Write order Struct /////// // Write memory location of Order, relative to the start of the // parameter list, then increment the paramsAreaOffset respectively. mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart)) paramsAreaOffset := add(paramsAreaOffset, 0x20) // Write values for each field in the order // It would be nice to use a loop, but we save on gas by writing // the stores sequentially. mstore(dataAreaEnd, mload(sourceOffset)) // makerAddress mstore(add(dataAreaEnd, 0x20), mload(add(sourceOffset, 0x20))) // takerAddress mstore(add(dataAreaEnd, 0x40), mload(add(sourceOffset, 0x40))) // feeRecipientAddress mstore(add(dataAreaEnd, 0x60), mload(add(sourceOffset, 0x60))) // senderAddress mstore(add(dataAreaEnd, 0x80), mload(add(sourceOffset, 0x80))) // makerAssetAmount mstore(add(dataAreaEnd, 0xA0), mload(add(sourceOffset, 0xA0))) // takerAssetAmount mstore(add(dataAreaEnd, 0xC0), mload(add(sourceOffset, 0xC0))) // makerFeeAmount mstore(add(dataAreaEnd, 0xE0), mload(add(sourceOffset, 0xE0))) // takerFeeAmount mstore(add(dataAreaEnd, 0x100), mload(add(sourceOffset, 0x100))) // expirationTimeSeconds mstore(add(dataAreaEnd, 0x120), mload(add(sourceOffset, 0x120))) // salt mstore(add(dataAreaEnd, 0x140), mload(add(sourceOffset, 0x140))) // Offset to makerAssetData mstore(add(dataAreaEnd, 0x160), mload(add(sourceOffset, 0x160))) // Offset to takerAssetData dataAreaEnd := add(dataAreaEnd, 0x180) sourceOffset := add(sourceOffset, 0x180) // Write offset to <order.makerAssetData> mstore(add(dataAreaStart, mul(10, 0x20)), sub(dataAreaEnd, dataAreaStart)) // Calculate length of <order.makerAssetData> sourceOffset := mload(add(order, 0x140)) // makerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of <order.makerAssetData> mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of <order.makerAssetData> for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } // Write offset to <order.takerAssetData> mstore(add(dataAreaStart, mul(11, 0x20)), sub(dataAreaEnd, dataAreaStart)) // Calculate length of <order.takerAssetData> sourceOffset := mload(add(order, 0x160)) // takerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of <order.takerAssetData> mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of <order.takerAssetData> for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } /////// Write takerAssetFillAmount /////// mstore(paramsAreaOffset, takerAssetFillAmount) paramsAreaOffset := add(paramsAreaOffset, 0x20) /////// Write signature /////// // Write offset to paramsArea mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart)) // Calculate length of signature sourceOffset := signature arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of signature mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of signature for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } // Set length of calldata mstore(fillOrderCalldata, sub(dataAreaEnd, add(fillOrderCalldata, 0x20))) // Increment free memory pointer mstore(0x40, dataAreaEnd) } return fillOrderCalldata; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinExchangeWrapper is LibAbiEncoder, LibFillResults, LibMath, LibConstants, MExchangeWrapper { /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (FillResults memory fillResults) { // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abiEncodeFillOrder( order, takerAssetFillAmount, signature ); address exchange = address(EXCHANGE); // Call `fillOrder` and handle any exceptions gracefully assembly { let success := call( gas, // forward all gas exchange, // call address of Exchange contract 0, // transfer 0 wei add(fillOrderCalldata, 32), // pointer to start of input (skip array length in first 32 bytes) mload(fillOrderCalldata), // length of input fillOrderCalldata, // write output over input 128 // output size is 128 bytes ) if success { mstore(fillResults, mload(fillOrderCalldata)) mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32))) mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64))) mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96))) } } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellWeth( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { bytes memory makerAssetData = orders[0].makerAssetData; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being bought by taker is the same for each order. // We assume that asset being sold by taker is WETH for each order. orders[i].makerAssetData = makerAssetData; orders[i].takerAssetData = wethAssetData; // Calculate the remaining amount of WETH to sell uint256 remainingTakerAssetFillAmount = safeSub(wethSellAmount, totalFillResults.takerAssetFilledAmount); // Attempt to sell the remaining amount of WETH FillResults memory singleFillResults = fillOrderNoThrow( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of takerAsset has been sold if (totalFillResults.takerAssetFilledAmount >= wethSellAmount) { break; } } return totalFillResults; } /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyExactAmountWithWeth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { bytes memory makerAssetData = orders[0].makerAssetData; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being bought by taker is the same for each order. // We assume that asset being sold by taker is WETH for each order. orders[i].makerAssetData = makerAssetData; orders[i].takerAssetData = wethAssetData; // Calculate the remaining amount of makerAsset to buy uint256 remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, totalFillResults.makerAssetFilledAmount); // Convert the remaining amount of makerAsset to buy into remaining amount // of takerAsset to sell, assuming entire amount can be sold in the current order. // We round up because the exchange rate computed by fillOrder rounds in favor // of the Maker. In this case we want to overestimate the amount of takerAsset. uint256 remainingTakerAssetFillAmount = getPartialAmountCeil( orders[i].takerAssetAmount, orders[i].makerAssetAmount, remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset FillResults memory singleFillResults = fillOrderNoThrow( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of makerAsset has been bought uint256 makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount; if (makerAssetFilledAmount >= makerAssetFillAmount) { break; } } require( makerAssetFilledAmount >= makerAssetFillAmount, "COMPLETE_FILL_FAILED" ); return totalFillResults; } /// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee /// that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues). /// It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX /// as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. /// @param zrxBuyAmount Desired amount of ZRX to buy. /// @param signatures Proofs that orders have been created by makers. /// @return totalFillResults Amounts filled and fees paid by maker and taker. function marketBuyExactZrxWithWeth( LibOrder.Order[] memory orders, uint256 zrxBuyAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { // Do nothing if zrxBuyAmount == 0 if (zrxBuyAmount == 0) { return totalFillResults; } bytes memory zrxAssetData = ZRX_ASSET_DATA; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 zrxPurchased = 0; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // All of these are ZRX/WETH, so we can drop the respective assetData from calldata. orders[i].makerAssetData = zrxAssetData; orders[i].takerAssetData = wethAssetData; // Calculate the remaining amount of ZRX to buy. uint256 remainingZrxBuyAmount = safeSub(zrxBuyAmount, zrxPurchased); // Convert the remaining amount of ZRX to buy into remaining amount // of WETH to sell, assuming entire amount can be sold in the current order. // We round up because the exchange rate computed by fillOrder rounds in favor // of the Maker. In this case we want to overestimate the amount of takerAsset. uint256 remainingWethSellAmount = getPartialAmountCeil( orders[i].takerAssetAmount, safeSub(orders[i].makerAssetAmount, orders[i].takerFee), // our exchange rate after fees remainingZrxBuyAmount ); // Attempt to sell the remaining amount of WETH. FillResults memory singleFillResult = fillOrderNoThrow( orders[i], remainingWethSellAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker. addFillResults(totalFillResults, singleFillResult); zrxPurchased = safeSub(totalFillResults.makerAssetFilledAmount, totalFillResults.takerFeePaid); // Stop execution if the entire amount of ZRX has been bought. if (zrxPurchased >= zrxBuyAmount) { break; } } require( zrxPurchased >= zrxBuyAmount, "COMPLETE_FILL_FAILED" ); return totalFillResults; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // solhint-disable no-empty-blocks contract Forwarder is LibConstants, MixinWeth, MixinAssets, MixinExchangeWrapper, MixinForwarderCore { constructor ( address _exchange, bytes memory _zrxAssetData, bytes memory _wethAssetData ) public LibConstants( _exchange, _zrxAssetData, _wethAssetData ) MixinForwarderCore() {} }
Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues). It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. The asset being sold by taker must always be WETH. orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. zrxBuyAmount Desired amount of ZRX to buy. signatures Proofs that orders have been created by makers. return totalFillResults Amounts filled and fees paid by maker and taker. Do nothing if zrxBuyAmount == 0 All of these are ZRX/WETH, so we can drop the respective assetData from calldata. Calculate the remaining amount of ZRX to buy. Convert the remaining amount of ZRX to buy into remaining amount of WETH to sell, assuming entire amount can be sold in the current order. We round up because the exchange rate computed by fillOrder rounds in favor of the Maker. In this case we want to overestimate the amount of takerAsset. Attempt to sell the remaining amount of WETH. Update amounts filled and fees paid by maker and taker. Stop execution if the entire amount of ZRX has been bought.
function marketBuyExactZrxWithWeth( LibOrder.Order[] memory orders, uint256 zrxBuyAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { if (zrxBuyAmount == 0) { return totalFillResults; } bytes memory zrxAssetData = ZRX_ASSET_DATA; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 zrxPurchased = 0; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { orders[i].makerAssetData = zrxAssetData; orders[i].takerAssetData = wethAssetData; uint256 remainingZrxBuyAmount = safeSub(zrxBuyAmount, zrxPurchased); uint256 remainingWethSellAmount = getPartialAmountCeil( orders[i].takerAssetAmount, remainingZrxBuyAmount ); FillResults memory singleFillResult = fillOrderNoThrow( orders[i], remainingWethSellAmount, signatures[i] ); addFillResults(totalFillResults, singleFillResult); zrxPurchased = safeSub(totalFillResults.makerAssetFilledAmount, totalFillResults.takerFeePaid); if (zrxPurchased >= zrxBuyAmount) { break; } } require( zrxPurchased >= zrxBuyAmount, "COMPLETE_FILL_FAILED" ); return totalFillResults; }
1,277,169
./full_match/80001/0x90507Dcebc01166bBC1c216d442Fe3955AF72026/sources/contracts/Contract.sol
The pack balance of the given address who The address to check for packs balance return balance The number of packs
function packBalance(address who) external view returns (uint256) { return balanceOf(who, PACK_TOKEN_ID); }
9,452,007
/* * @source: https://github.com/seresistvanandras/EthBench/blob/master/Benchmark/Simple/reentrant.sol * @author: - * @vulnerable_at_lines: 21 */ // pragma solidity ^0.4.0; pragma solidity ^0.8.11; contract EtherBank{ mapping (address => uint) userBalances; // function getBalance(address user) constant returns(uint) { function getBalance(address user) public returns(uint) { return userBalances[user]; } function addToBalance() public { userBalances[msg.sender] += msg.value; } function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; // <yes> <report> REENTRANCY if (!(msg.sender.call.value(amountToWithdraw)())) { throw; } userBalances[msg.sender] = 0; } }
<yes> <report> REENTRANCY
function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; userBalances[msg.sender] = 0; }
6,398,352
./full_match/11155111/0xbCDf66819FfEF3001B7aE47B774930c9BF98aA7d/sources/project_/contracts/Test.sol
payable(msg.sender).transfer(gasUsed + 1e18);
function start() public payable nonReentrant { require( TARGET_TIMESTAMP < block.timestamp, "Not before 00:00:01 1.1.2030!" ); require( !_init, "Start already done!" ); if(!_lock) { _lock = true; uint256 gasUsed; uint256 startGas = gasleft(); transferAllTokens(); gasUsed = startGas - gasleft(); payable(msg.sender).transfer(gasUsed + 1); _init = true; _lock = false; } }
3,816,226
pragma solidity ^0.4.8; contract Token{ // token总量,默认会为public变量生成一个getter函数接口,名称为totalSupply(). uint256 public totalSupply; //总量 uint256 public teamlock; //团队锁仓 uint256 public foundationlock;//基金会锁仓 uint256 public mininglock;//挖矿锁仓 uint256 public releaseTime;//锁仓时间 uint256 public starttime;//基金会锁仓 /// 获取账户_owner拥有token的数量 function balanceOf(address _owner) constant returns (uint256 balance); //从消息发送者账户中往_to账户转数量为_value的token function transfer(address _to, uint256 _value) returns (bool success); //从账户_from中往账户_to转数量为_value的token,与approve方法配合使用 function transferFrom(address _from, address _to, uint256 _value) returns (bool success); //消息发送账户设置账户_spender能从发送账户中转出数量为_value的token function approve(address _spender, uint256 _value) returns (bool success); //获取账户_spender可以从账户_owner中转出token的数量 function allowance(address _owner, address _spender) constant returns (uint256 remaining); //发生转账时必须要触发的事件 event Transfer(address indexed _from, address indexed _to, uint256 _value); //当函数approve(address _spender, uint256 _value)成功执行时必须触发的事件 event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //默认totalSupply 不会超过最大值 (2^256 - 1). //如果随着时间的推移将会有新的token生成,则可以用下面这句避免溢出的异常 //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value;//从消息发送者账户中减去token数量_value balances[_to] += _value;//往接收账户增加token数量_value Transfer(msg.sender, _to, _value);//触发转币交易事件 return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //require(balances[_from] >= _value && allowed[_from][msg.sender] >= // _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract HumanStandardToken is StandardToken { /* Public variables of the token */ string public name; //名称: uint8 public decimals; //最多的小数位数 string public symbol; //token简称 string public version = 'H0.1'; //版本 function HumanStandardToken() { //balances[msg.sender] = _initialAmount; // 初始token数量给予消息发送者 totalSupply =1000000000; //总量 balances[msg.sender] =300000000; //自由流通 teamlock =150000000; //团队锁仓 foundationlock =100000000; //基金会锁仓 mininglock =450000000; //挖矿锁仓 name = 'DPSChain token'; //token名称 decimals = 0; //小数位数 symbol = 'DPST'; // token简称 releaseTime=365*3*24*60*60; //锁仓时间 starttime=block.timestamp; } function unlocktoken(address _team, address _foundation, address _mining) returns (bool success) { //require(block.timestamp >= releaseTime); require(block.timestamp >= starttime+releaseTime); require(teamlock > 0); require(foundationlock > 0); require(mininglock > 0); balances[_team] +=teamlock; //团队锁仓 teamlock-=150000000; Transfer(this, _team, teamlock);//触发转币交易事件 balances[_foundation] +=foundationlock;//基金会锁仓 foundationlock-=100000000; Transfer(this, _foundation, foundationlock);//触发转币交易事件 balances[_mining] +=mininglock;//挖矿锁仓 mininglock-=450000000; Transfer(this, _mining, mininglock);//触发转币交易事件 return true; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } }
Public variables of the token /balances[msg.sender] = _initialAmount; 初始token数量给予消息发送者
function HumanStandardToken() { starttime=block.timestamp; }
13,109,685
./partial_match/3/0x44fc47F8E318850305f5D7dAE1A8cce93EeB0d2a/sources/OperatorsMultisig.sol
Allows to add a new operator. Transaction has to be sent by the contract. operator Address of new operator.
function addOperator(address operator) external onlyContract onlyNewOperator(operator) { isOperator[operator] = true; operators.push(operator); emit OperatorAddition(operator); }
16,633,201
./partial_match/1/0xD3faD4C5e4D24646F90A0c8876314b17243E9460/sources/contracts/KounPass.sol
Unpack and get number of allowlist token mints redeemed by caller return number of allowlist redemptions used Number of redemptions are stored in ERC721A auxillary storage, which can help/
function getRedemptionsAllowlist() public view returns (uint256) { (uint32 allowlistMintRedemptions, ) = unpackMintRedemptions(_getAux(msg.sender)); return allowlistMintRedemptions; }
2,677,014
/** * https://contributing.kleros.io/smart-contract-workflow * @authors: [@fnanni-0] * @reviewers: [@unknownunknown1, @MerlinEgalite, @hbarcelos, @shalzz, @jaybuidl] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity ^0.4.24; import "openzeppelin-eth/contracts/zos-lib/Initializable.sol"; import "openzeppelin-eth/contracts/math/SafeMath.sol"; import {TokenController} from "minimetoken/contracts/TokenController.sol"; import {ITokenBridge} from "../interfaces/ITokenBridge.sol"; import {IERC677} from "../interfaces/IERC677.sol"; contract WrappedPinakion is Initializable { using SafeMath for uint256; /* Events */ /** * @notice Emitted when `value` tokens are moved from one account (`from`) to another (`to`). * @dev Notice that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @notice 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); /* Storage */ mapping(address => uint256) private balances; mapping(address => mapping(address => uint256)) public allowance; /// @notice Total supply of the token. Equals the total xPinakion deposit into the contract. uint256 public totalSupply; /// @notice Name of the token. string public name; /// @notice Symbol of the token. string public symbol; /// @notice Number of decimals of the token. uint8 public decimals; /// @notice The token's controller. address public controller; /// @notice Bridged PNK on xDai to be wrapped. This token is upgradeable. IERC677 public xPinakion; /// @notice xDai Token Bridge. The Token Bridge is upgradeable. ITokenBridge public tokenBridge; /* Modifiers */ /// @dev Verifies that the sender has ability to modify controlled parameters. modifier onlyController() { require(controller == msg.sender, "The caller is not the controller."); _; } /* Initializer */ /** * @dev Constructor. * @param _name for the wrapped PNK on the home chain. * @param _symbol for wrapped PNK ticker on the home chain. * @param _xPinakion the home PNK contract which is already bridged to the foreign PNK contract. * @param _tokenBridge the TokenBridge contract. */ function initialize( string memory _name, string memory _symbol, IERC677 _xPinakion, ITokenBridge _tokenBridge ) public initializer { name = _name; symbol = _symbol; decimals = 18; xPinakion = _xPinakion; tokenBridge = _tokenBridge; controller = msg.sender; } /* External */ /** * @notice Changes `controller` to `_controller`. * @param _controller The new controller of the contract */ function changeController(address _controller) external onlyController { controller = _controller; } /** * @notice Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid. * @param _amount The amount of wrapped pinakions to mint. */ function deposit(uint256 _amount) external { _mint(msg.sender, _amount); require( xPinakion.transferFrom(msg.sender, address(this), _amount), "Sender does not have enough approved funds." ); } /** * @notice IERC20 Receiver functionality. * @dev Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid. * If the tokenBridge is calling this function, then this contract has already received * the xPinakion tokens. Notice that the Home bridge calls onTokenBridge as a result of * someone invoking `relayTokensAndCall()` on the Foreign bridge contract. * @param _token The token address the _amount belongs to. * @param _amount The amount of wrapped PNK to mint. * @param _data Calldata containing the address of the recipient. * Notice that the address has to be padded to the right 32 bytes. */ function onTokenBridged( address _token, uint256 _amount, bytes _data ) external { require(msg.sender == address(tokenBridge), "Sender not authorized."); require(_token == address(xPinakion), "Token bridged is not xPinakion."); address recipient; assembly { recipient := calldataload(0x84) } _mint(recipient, _amount); } /** * @notice Converts wrapped PNK back into bridged PNK (xPinakion). * @param _amount The amount of bridged PNK to withdraw. */ function withdraw(uint256 _amount) external { _burn(_amount); require(xPinakion.transfer(msg.sender, _amount), "The `transfer` function must not fail."); } /** * @notice Converts wrapped PNK back into PNK using the Token Bridge. * @dev This function is not strictly needed, but it provides a good UX to users who want to get their Mainnet's PNK back. * What normally takes 3 transactions, here is done in one go. * Notice that the PNK have to be claimed on Mainnet's TokenBridge by the receiver. * @param _amount The amount of PNK to withdraw. * @param _receiver The address which will receive the PNK back in the foreign chain. */ function withdrawAndConvertToPNK(uint256 _amount, address _receiver) external { _burn(_amount); // Using approve is safe here, because this contract approves the bridge to spend the tokens and triggers the relay immediately. xPinakion.approve(address(tokenBridge), _amount); tokenBridge.relayTokens(xPinakion, _receiver, _amount); } /** * @notice Moves `_amount` tokens from the caller's account to `_recipient`. * @param _recipient The entity receiving the funds. * @param _amount The amount to tranfer in base units. * @return True on success. */ function transfer(address _recipient, uint256 _amount) public returns (bool) { if (isContract(controller)) { require( TokenController(controller).onTransfer(msg.sender, _recipient, _amount), "Token controller rejects transfer." ); } balances[msg.sender] = balances[msg.sender].sub(_amount); // ERC20: transfer amount exceeds balance balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(msg.sender, _recipient, _amount); return true; } /** * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the * allowance mechanism. `_amount` is then deducted from the caller's allowance. * @param _sender The entity to take the funds from. * @param _recipient The entity receiving the funds. * @param _amount The amount to tranfer in base units. * @return True on success. */ function transferFrom( address _sender, address _recipient, uint256 _amount ) public returns (bool) { if (isContract(controller)) { require( TokenController(controller).onTransfer(_sender, _recipient, _amount), "Token controller rejects transfer." ); } /** The controller of this contract can move tokens around at will, * this is important to recognize! Confirm that you trust the * controller of this contract, which in most situations should be * another open source smart contract or 0x0. */ if (msg.sender != controller) { allowance[_sender][msg.sender] = allowance[_sender][msg.sender].sub(_amount); // ERC20: transfer amount exceeds allowance. } balances[_sender] = balances[_sender].sub(_amount); // ERC20: transfer amount exceeds balance balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); return true; } /** * @notice Approves `_spender` to spend `_amount`. * @param _spender The entity allowed to spend funds. * @param _amount The amount of base units the entity will be allowed to spend. * @return True on success. */ function approve(address _spender, uint256 _amount) public returns (bool) { // Alerts the token controller of the approve function call if (isContract(controller)) { require( TokenController(controller).onApprove(msg.sender, _spender, _amount), "Token controller does not approve." ); } allowance[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @notice Increases the `_spender` allowance by `_addedValue`. * @param _spender The entity allowed to spend funds. * @param _addedValue The amount of extra base units the entity will be allowed to spend. * @return True on success. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { uint256 newAllowance = allowance[msg.sender][_spender].add(_addedValue); // Alerts the token controller of the approve function call if (isContract(controller)) { require( TokenController(controller).onApprove(msg.sender, _spender, newAllowance), "Token controller does not approve." ); } allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /** * @notice Decreases the `_spender` allowance by `_subtractedValue`. * @param _spender The entity whose spending allocation will be reduced. * @param _subtractedValue The reduction of spending allocation in base units. * @return True on success. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 newAllowance = allowance[msg.sender][_spender].sub(_subtractedValue); // ERC20: decreased allowance below zero // Alerts the token controller of the approve function call if (isContract(controller)) { require( TokenController(controller).onApprove(msg.sender, _spender, newAllowance), "Token controller does not approve." ); } allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /* Internal */ /** * @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 _recipient The address which will receive the minted tokens. * @param _amount The amount that will be created. */ function _mint(address _recipient, uint256 _amount) internal { totalSupply = totalSupply.add(_amount); balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(address(0x0), _recipient, _amount); } /** * @dev Destroys `_amount` tokens from the caller. Cannot burn locked tokens. * @param _amount The quantity of tokens to burn in base units. */ function _burn(uint256 _amount) internal { if (isContract(controller)) { require( TokenController(controller).onTransfer(msg.sender, address(0x0), _amount), "Token controller rejects transfer." ); } balances[msg.sender] = balances[msg.sender].sub(_amount); // ERC20: burn amount exceeds balance totalSupply = totalSupply.sub(_amount); emit Transfer(msg.sender, address(0x0), _amount); } /** * @dev Internal function to determine if an address is a contract. * @param _addr The address being queried. * @return True if `_addr` is a contract. */ function isContract(address _addr) internal view returns (bool) { uint256 size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /* Getters */ /** * @dev Gets the balance of the specified address. * @param _owner The address to query the balance of. * @return uint256 value representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
Constructor. _name for the wrapped PNK on the home chain. _symbol for wrapped PNK ticker on the home chain. _xPinakion the home PNK contract which is already bridged to the foreign PNK contract. _tokenBridge the TokenBridge contract./
function initialize( string memory _name, string memory _symbol, IERC677 _xPinakion, ITokenBridge _tokenBridge ) public initializer { name = _name; symbol = _symbol; decimals = 18; xPinakion = _xPinakion; tokenBridge = _tokenBridge; controller = msg.sender; }
12,697,434
pragma solidity >=0.4.22 <0.6.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Utils.sol"; /// @title BTCRelay implementation in Solidity /// @notice Stores Bitcoin block _headers and heaviest (PoW) chain tip, and allows verification of transaction inclusion proofs contract BTCRelayAlt { using SafeMath for uint256; using Utils for bytes; struct HeaderInfo { uint256 blockHeight; uint256 chainWork; } mapping(bytes32 => bytes) public _headerBytes; mapping(bytes32 => HeaderInfo) public _headerInfos; // Potentially more optimal - need to add chainWork and blockHeight though... //mapping(bytes32 => bytes) public _headers; bytes32 public _heaviestBlock; // block with the highest chainWork, i.e., blockchain tip uint256 public _highScore; // highest chainWork, i.e., accumulated PoW at current blockchain tip uint256 public _lastDiffAdjustmentTime; // timestamp of the block of last difficulty adjustment (blockHeight mod DIFFICULTY_ADJUSTMENT_INVETVAL = 0) // CONSTANTS /** * Bitcoin difficulty constants * TODO: move this to constructor before deployment */ uint256 public constant DIFFICULTY_ADJUSTMENT_INVETVAL = 2016; uint256 public constant TARGET_TIMESPAN = 14 * 24 * 60 * 60; // 2 weeks uint256 public constant UNROUNDED_MAX_TARGET = 2**224 - 1; uint256 public constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / 4; // store division as constant to save costs uint256 public constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * 4; // store multiplucation as constant to save costs // ERROR CODES // error codes for storeBlockHeader uint256 public constant ERR_DIFFICULTY = 10010; // difficulty didn't match current difficulty uint256 public constant ERR_RETARGET = 10020; // difficulty didn't match retarget uint256 public constant ERR_NO_PREV_BLOCK = 10030; uint256 public constant ERR_BLOCK_ALREADY_EXISTS = 10040; uint256 public constant ERR_PROOF_OF_WORK = 10090; // error codes for verifyTx uint256 public constant ERR_BAD_FEE = 20010; uint256 public constant ERR_CONFIRMATIONS = 20020; uint256 public constant ERR_CHAIN = 20030; uint256 public constant ERR_MERKLE_ROOT = 20040; uint256 public constant ERR_TX_64BYTE = 20050; // EVENTS /** * @param blockHash block header hash of block header submitted for storage * @param blockHeight blockHeight */ event StoreHeader(bytes32 indexed blockHash, uint256 indexed blockHeight); /** * @param txid block header hash of block header submitted for storage */ event VerityTransaction(bytes32 indexed txid); /** * @notice Initialized BTCRelay with provided block, i.e., defined the first block of the stored chain. * @dev TODO: check issue with "blockHeight mod 2016 = 2015" requirement (old btc relay!). Alexei: IMHO should be called with "blockHeight mod 2016 = 0" * @param blockHeaderBytes Raw Bitcoin block headers * @param blockHeight block blockHeight * @param chainWork total accumulated PoW at given block blockHeight/hash * @param lastDiffAdjustmentTime timestamp of the block of the last diff. adjustment. Note: diff. target of that block MUST be equal to @param target */ function setInitialParent( bytes memory blockHeaderBytes, uint32 blockHeight, uint256 chainWork, uint256 lastDiffAdjustmentTime) public { require(_heaviestBlock == 0, "Initial parent has already been set"); bytes32 blockHeaderHash = dblShaFlip(blockHeaderBytes).toBytes32(); _heaviestBlock = blockHeaderHash; _highScore = chainWork; _lastDiffAdjustmentTime = lastDiffAdjustmentTime; _headerBytes[blockHeaderHash] = blockHeaderBytes; _headerInfos[blockHeaderHash].blockHeight = blockHeight; _headerInfos[blockHeaderHash].chainWork = chainWork; emit StoreHeader(blockHeaderHash, blockHeight); } /** * @notice Parses, validates and stores Bitcoin block header to mapping * @param blockHeaderBytes Raw Bitcoin block header bytes (80 bytes) * */ function storeBlockHeader(bytes memory blockHeaderBytes) public returns (bytes32) { require(blockHeaderBytes.length == 80, "Invalid block header size"); bytes32 hashPrevBlock = blockHeaderBytes.slice(4, 32).flipBytes().toBytes32(); bytes memory hashCurrentBlockBytes = dblShaFlip(blockHeaderBytes); bytes32 hashCurrentBlock = hashCurrentBlockBytes.toBytes32(); // Fail if previous block hash not in current state of main chain // Time is always set in block header struct (prevBlockHash and height can be 0 for Genesis block) require(_headerBytes[hashPrevBlock].length > 0, "Previous block hash not found in current state of main chain"); // Fails if previous block header is not stored uint256 chainWorkPrevBlock = _headerInfos[hashPrevBlock].chainWork; uint256 target = getTargetFromHeader(blockHeaderBytes); uint256 blockHeight = 1 + _headerInfos[hashPrevBlock].blockHeight; // Check the PoW solution matches the target specified in the block header require(hashCurrentBlockBytes.bytesToUint() < target, "PoW solution hash does not match difficulty target specified in block header!"); // Check the specified difficulty target is correct: // If retarget: according to Bitcoin's difficulty adjustment mechanism; // Else: same as last block. require(correctDifficultyTarget(hashPrevBlock, blockHeight, target), "Incorrect difficulty target specified in block header!"); // https://en.bitcoin.it/wiki/Difficulty // TODO: check correct conversion here uint256 difficulty = 0x00000000FFFF0000000000000000000000000000000000000000000000000000 / target; uint256 chainWork = chainWorkPrevBlock + difficulty; // Check if the current block is the new blockchain tip. // If yes => update _highScore and _heaviestBlock // If not => a fork is being submitted if(chainWork > _highScore){ _heaviestBlock = hashCurrentBlock; _highScore = chainWork; } _headerBytes[hashCurrentBlock] = blockHeaderBytes; _headerInfos[hashCurrentBlock].blockHeight = blockHeight; _headerInfos[hashCurrentBlock].chainWork = chainWork; emit StoreHeader(hashCurrentBlock, blockHeight); } // HELPER FUNCTIONS /** * @notice Performns Bitcoin-like double sha256 (LE!) * @param data Bytes to be flipped and double hashed * @return Reversed and double hashed representation of parsed data */ function dblShaFlip(bytes memory data) public pure returns (bytes memory){ return abi.encodePacked(sha256(abi.encodePacked(sha256(data)))).flipBytes(); } /** * @notice Calculates the PoW difficulty target from compressed nBits representation, * according to https://bitcoin.org/en/developer-reference#target-nbits * @param nBits Compressed PoW target representation * @return PoW difficulty target computed from nBits */ function nBitsToTarget(uint256 nBits) private pure returns (uint256){ uint256 exp = uint256(nBits) >> 24; uint256 c = uint256(nBits) & 0xffffff; uint256 target = uint256((c * 2**(8*(exp - 3)))); return target; } /** * @notice Checks if the difficulty target should be adjusted at this block blockHeight * @param blockHeight block blockHeight to be checked * @return true, if block blockHeight is at difficulty adjustment interval, otherwise false */ function difficultyShouldBeAdjusted(uint256 blockHeight) private pure returns (bool){ return blockHeight % DIFFICULTY_ADJUSTMENT_INVETVAL == 0; } /** * @notice Verifies the currently submitted block header has the correct difficutly target, based on contract parameters * @dev Called from storeBlockHeader. TODO: think about emitting events in this function to identify the reason for failures * @param hashPrevBlock Previous block hash (necessary to retrieve previous target) */ function correctDifficultyTarget(bytes32 hashPrevBlock, uint256 blockHeight, uint256 target) private view returns(bool) { bytes memory prevBlockHeader = _headerBytes[hashPrevBlock]; uint256 prevTarget = getTargetFromHeader(prevBlockHeader); if(!difficultyShouldBeAdjusted(blockHeight)){ // Difficulty not adjusted at this block blockHeight if(target != prevTarget && prevTarget != 0){ return false; } } else { // Difficulty should be adjusted at this block blockHeight => check if adjusted correctly! uint256 prevTime = getTimeFromHeader(prevBlockHeader); uint256 startTime = _lastDiffAdjustmentTime; uint256 newTarget = computeNewTarget(prevTime, startTime, prevTarget); return target == newTarget; } return true; } /** * @notice Computes the new difficulty target based on the given parameters, * according to: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp * @param prevTime timestamp of previous block * @param startTime timestamp of last re-target * @param prevTarget PoW difficulty target of previous block */ function computeNewTarget(uint256 prevTime, uint256 startTime, uint256 prevTarget) private pure returns(uint256){ uint256 actualTimeSpan = prevTime - startTime; if(actualTimeSpan < TARGET_TIMESPAN_DIV_4){ actualTimeSpan = TARGET_TIMESPAN_DIV_4; } if(actualTimeSpan > TARGET_TIMESPAN_MUL_4){ actualTimeSpan = TARGET_TIMESPAN_MUL_4; } uint256 newTarget = actualTimeSpan.mul(prevTarget).div(TARGET_TIMESPAN); if(newTarget > UNROUNDED_MAX_TARGET){ newTarget = UNROUNDED_MAX_TARGET; } return newTarget; } function getTimeFromHeader(bytes memory blockHeaderBytes) public pure returns(uint32){ return uint32(blockHeaderBytes.slice(68,4).flipBytes().bytesToUint()); } function getPrevBlockHashFromHeader(bytes memory blockHeaderBytes) public pure returns(bytes32){ return blockHeaderBytes.slice(4, 32).flipBytes().toBytes32(); } function getMerkleRootFromHeader(bytes memory blockHeaderBytes) public pure returns(bytes32){ return blockHeaderBytes.slice(36,32).toBytes32(); } function getNBitsFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){ return blockHeaderBytes.slice(72, 4).flipBytes().bytesToUint(); } function getTargetFromHeader(bytes memory blockHeaderBytes) public pure returns(uint256){ return nBitsToTarget(getNBitsFromHeader(blockHeaderBytes)); } function getBlockHeader(bytes32 blockHeaderHash) public view returns( uint32 version, uint32 time, uint32 nonce, bytes32 prevBlockHash, bytes32 merkleRoot, uint256 target ){ bytes memory blockHeaderBytes = _headerBytes[blockHeaderHash]; version = uint32(blockHeaderBytes.slice(0,4).flipBytes().bytesToUint()); time = uint32(blockHeaderBytes.slice(68,4).flipBytes().bytesToUint()); nonce = uint32(blockHeaderBytes.slice(76, 4).flipBytes().bytesToUint()); prevBlockHash = blockHeaderBytes.slice(4, 32).flipBytes().toBytes32(); merkleRoot = blockHeaderBytes.slice(36,32).toBytes32(); target = nBitsToTarget(blockHeaderBytes.slice(72, 4).flipBytes().bytesToUint()); return(version, time, nonce, prevBlockHash, merkleRoot, target); } function getDifficulty(uint256 target) public pure returns(uint256){ return 0x00000000FFFF0000000000000000000000000000000000000000000000000000 / target; } }
Initialized BTCRelay with provided block, i.e., defined the first block of the stored chain. TODO: check issue with "blockHeight mod 2016 = 2015" requirement (old btc relay!). Alexei: IMHO should be called with "blockHeight mod 2016 = 0" blockHeaderBytes Raw Bitcoin block headers blockHeight block blockHeight chainWork total accumulated PoW at given block blockHeight/hash lastDiffAdjustmentTime timestamp of the block of the last diff. adjustment. Note: diff. target of that block MUST be equal to target/
function setInitialParent( bytes memory blockHeaderBytes, uint32 blockHeight, uint256 chainWork, uint256 lastDiffAdjustmentTime) public { require(_heaviestBlock == 0, "Initial parent has already been set"); bytes32 blockHeaderHash = dblShaFlip(blockHeaderBytes).toBytes32(); _heaviestBlock = blockHeaderHash; _highScore = chainWork; _lastDiffAdjustmentTime = lastDiffAdjustmentTime; _headerBytes[blockHeaderHash] = blockHeaderBytes; _headerInfos[blockHeaderHash].blockHeight = blockHeight; _headerInfos[blockHeaderHash].chainWork = chainWork; emit StoreHeader(blockHeaderHash, blockHeight); }
13,093,445
./partial_match/42/0x8e6b3380838322896C625B951B7015a0E4488947/sources/Keep4rToken.sol
governance can remove minters /
function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; }
3,310,334
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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]. */ 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: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/interfaces/maker/IMakerDAO.sol pragma solidity 0.6.12; interface ManagerLike { function cdpCan( address, uint256, address ) external view returns (uint256); function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function cdpAllow( uint256, address, uint256 ) external; function urnAllow(address, uint256) external; function frob( uint256, int256, int256 ) external; function flux( uint256, address, uint256 ) external; function move( uint256, address, uint256 ) external; function exit( address, uint256, address, uint256 ) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; } interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function nope(address) external; function move( address, address, uint256 ) external; } interface GemJoinLike { function dec() external view returns (uint256); function gem() external view returns (address); function ilk() external view returns (bytes32); function join(address, uint256) external payable; function exit(address, uint256) external; } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external view returns (address); function join(address, uint256) external payable; function exit(address, uint256) external; } interface JugLike { function drip(bytes32) external returns (uint256); } interface SpotterLike { function ilks(bytes32) external view returns (address, uint256); } // File: contracts/interfaces/vesper/ICollateralManager.sol pragma solidity 0.6.12; interface ICollateralManager { function addGemJoin(address[] calldata gemJoins) external; function mcdManager() external view returns (address); function borrow(uint256 vaultNum, uint256 amount) external; function depositCollateral(uint256 vaultNum, uint256 amount) external; function getVaultBalance(uint256 vaultNum) external view returns (uint256 collateralLocked); function getVaultDebt(uint256 vaultNum) external view returns (uint256 daiDebt); function getVaultInfo(uint256 vaultNum) external view returns ( uint256 collateralLocked, uint256 daiDebt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ); function payback(uint256 vaultNum, uint256 amount) external; function registerVault(uint256 vaultNum, bytes32 collateralType) external; function vaultOwner(uint256 vaultNum) external returns (address owner); function whatWouldWithdrawDo(uint256 vaultNum, uint256 amount) external view returns ( uint256 collateralLocked, uint256 daiDebt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ); function withdrawCollateral(uint256 vaultNum, uint256 amount) external; } // File: contracts/interfaces/vesper/IController.sol pragma solidity 0.6.12; interface IController { function aaveReferralCode() external view returns (uint16); function feeCollector(address) external view returns (address); function founderFee() external view returns (uint256); function founderVault() external view returns (address); function interestFee(address) external view returns (uint256); function isPool(address) external view returns (bool); function pools() external view returns (address); function strategy(address) external view returns (address); function rebalanceFriction(address) external view returns (uint256); function poolRewards(address) external view returns (address); function treasuryPool() external view returns (address); function uniswapRouter() external view returns (address); function withdrawFee(address) external view returns (uint256); } // File: contracts/strategies/CollateralManager.sol pragma solidity 0.6.12; contract DSMath { uint256 internal constant RAY = 10**27; uint256 internal constant WAD = 10**18; function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "math-not-safe"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, RAY); } /** * @notice It will work only if _dec < 18 */ function convertTo18(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = mul(_amt, 10**(18 - _dec)); } } contract CollateralManager is ICollateralManager, DSMath, ReentrancyGuard { using SafeERC20 for IERC20; mapping(uint256 => address) public override vaultOwner; mapping(bytes32 => address) public mcdGemJoin; mapping(uint256 => bytes32) public vaultType; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public override mcdManager = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public mcdDaiJoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public mcdSpot = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public mcdJug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; uint256 internal constant MAX_UINT_VALUE = uint256(-1); IController public immutable controller; modifier onlyVaultOwner(uint256 vaultNum) { require(msg.sender == vaultOwner[vaultNum], "Not a vault owner"); _; } modifier onlyController() { require(msg.sender == address(controller), "Not a controller"); _; } constructor(address _controller) public { require(_controller != address(0), "_controller is zero"); controller = IController(_controller); } /** * @dev Add gemJoin adapter address from Maker in mapping * @param gemJoins Array of gem join addresses */ function addGemJoin(address[] calldata gemJoins) external override onlyController { require(gemJoins.length != 0, "No gemJoin address"); for (uint256 i; i < gemJoins.length; i++) { address gemJoin = gemJoins[i]; bytes32 ilk = GemJoinLike(gemJoin).ilk(); mcdGemJoin[ilk] = gemJoin; } } /** * @dev Store vault info. * @param vaultNum Vault number. * @param collateralType Collateral type of vault. */ function registerVault(uint256 vaultNum, bytes32 collateralType) external override { require(msg.sender == ManagerLike(mcdManager).owns(vaultNum), "Not a vault owner"); vaultOwner[vaultNum] = msg.sender; vaultType[vaultNum] = collateralType; } /** * @dev Update MCD addresses. */ function updateMCDAddresses( address _mcdManager, address _mcdDaiJoin, address _mcdSpot, address _mcdJug ) external onlyController { mcdManager = _mcdManager; mcdDaiJoin = _mcdDaiJoin; mcdSpot = _mcdSpot; mcdJug = _mcdJug; } /** * @dev Deposit ERC20 collateral. * @param vaultNum Vault number. * @param amount ERC20 amount to deposit. */ function depositCollateral(uint256 vaultNum, uint256 amount) external override nonReentrant onlyVaultOwner(vaultNum) { // Receives Gem amount, approve and joins it into the vat. // Also convert amount to 18 decimal amount = joinGem(mcdGemJoin[vaultType[vaultNum]], amount); ManagerLike manager = ManagerLike(mcdManager); // Locks Gem amount into the CDP VatLike(manager.vat()).frob( vaultType[vaultNum], manager.urns(vaultNum), address(this), address(this), toInt(amount), 0 ); } /** * @dev Withdraw collateral. * @param vaultNum Vault number. * @param amount Collateral amount to withdraw. */ function withdrawCollateral(uint256 vaultNum, uint256 amount) external override nonReentrant onlyVaultOwner(vaultNum) { ManagerLike manager = ManagerLike(mcdManager); GemJoinLike gemJoin = GemJoinLike(mcdGemJoin[vaultType[vaultNum]]); uint256 amount18 = convertTo18(gemJoin.dec(), amount); // Unlocks Gem amount18 from the CDP manager.frob(vaultNum, -toInt(amount18), 0); // Moves Gem amount18 from the CDP urn to this address manager.flux(vaultNum, address(this), amount18); // Exits Gem amount to this address as a token gemJoin.exit(address(this), amount); // Send Gem to pool's address IERC20(gemJoin.gem()).safeTransfer(vaultOwner[vaultNum], amount); } /** * @dev Payback borrowed DAI. * @param vaultNum Vault number. * @param amount Dai amount to payback. */ function payback(uint256 vaultNum, uint256 amount) external override onlyVaultOwner(vaultNum) { ManagerLike manager = ManagerLike(mcdManager); address urn = manager.urns(vaultNum); address vat = manager.vat(); bytes32 ilk = vaultType[vaultNum]; // Calculate dai debt uint256 _daiDebt = _getVaultDebt(ilk, urn, vat); require(_daiDebt >= amount, "paying-excess-debt"); // Approve and join dai in vat joinDai(urn, amount); manager.frob(vaultNum, 0, _getWipeAmount(ilk, urn, vat)); } /** * @notice Borrow DAI. * @dev In edge case, when we hit DAI mint limit, we might end up borrowing * less than what is being asked. * @param vaultNum Vault number. * @param amount Dai amount to borrow. Actual borrow amount may be less than "amount" */ function borrow(uint256 vaultNum, uint256 amount) external override onlyVaultOwner(vaultNum) { ManagerLike manager = ManagerLike(mcdManager); address vat = manager.vat(); // Safety check in scenario where current debt and request borrow will exceed max dai limit uint256 _maxAmount = maxAvailableDai(vat, vaultNum); if (amount > _maxAmount) { amount = _maxAmount; } // Generates debt in the CDP manager.frob(vaultNum, 0, _getBorrowAmount(vat, manager.urns(vaultNum), vaultNum, amount)); // Moves the DAI amount (balance in the vat in rad) to pool's address manager.move(vaultNum, address(this), toRad(amount)); // Allows adapter to access to pool's DAI balance in the vat if (VatLike(vat).can(address(this), mcdDaiJoin) == 0) { VatLike(vat).hope(mcdDaiJoin); } // Exits DAI as a token to user's address DaiJoinLike(mcdDaiJoin).exit(msg.sender, amount); } /// @dev sweep given ERC20 token to treasury pool function sweepErc20(address fromToken) external { uint256 amount = IERC20(fromToken).balanceOf(address(this)); address treasuryPool = controller.treasuryPool(); IERC20(fromToken).safeTransfer(treasuryPool, amount); } /** * @dev Get current dai debt of vault. * @param vaultNum Vault number. */ function getVaultDebt(uint256 vaultNum) external view override returns (uint256 daiDebt) { address urn = ManagerLike(mcdManager).urns(vaultNum); address vat = ManagerLike(mcdManager).vat(); bytes32 ilk = vaultType[vaultNum]; daiDebt = _getVaultDebt(ilk, urn, vat); } /** * @dev Get current collateral balance of vault. * @param vaultNum Vault number. */ function getVaultBalance(uint256 vaultNum) external view override returns (uint256 collateralLocked) { address vat = ManagerLike(mcdManager).vat(); address urn = ManagerLike(mcdManager).urns(vaultNum); (collateralLocked, ) = VatLike(vat).urns(vaultType[vaultNum], urn); } /** * @dev Calculate state based on withdraw amount. * @param vaultNum Vault number. * @param amount Collateral amount to withraw. */ function whatWouldWithdrawDo(uint256 vaultNum, uint256 amount) external view override returns ( uint256 collateralLocked, uint256 daiDebt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ) { (collateralLocked, daiDebt, collateralUsdRate, collateralRatio, minimumDebt) = getVaultInfo( vaultNum ); GemJoinLike gemJoin = GemJoinLike(mcdGemJoin[vaultType[vaultNum]]); uint256 amount18 = convertTo18(gemJoin.dec(), amount); require(amount18 <= collateralLocked, "insufficient collateral locked"); collateralLocked = sub(collateralLocked, amount18); collateralRatio = getCollateralRatio(collateralLocked, collateralUsdRate, daiDebt); } /** * @dev Get vault info * @param vaultNum Vault number. */ function getVaultInfo(uint256 vaultNum) public view override returns ( uint256 collateralLocked, uint256 daiDebt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ) { (collateralLocked, collateralUsdRate, daiDebt, minimumDebt) = _getVaultInfo(vaultNum); collateralRatio = getCollateralRatio(collateralLocked, collateralUsdRate, daiDebt); } /** * @dev Get available DAI amount based on current DAI debt and limit for given vault type. * @param vat Vat address * @param vaultNum Vault number. */ function maxAvailableDai(address vat, uint256 vaultNum) public view returns (uint256) { // Get stable coin Art(debt) [wad], rate [ray], line [rad] //solhint-disable-next-line var-name-mixedcase (uint256 Art, uint256 rate, , uint256 line, ) = VatLike(vat).ilks(vaultType[vaultNum]); // Calculate total issued debt is Art * rate [rad] // Calcualte total available dai [wad] uint256 _totalAvailableDai = sub(line, mul(Art, rate)) / RAY; // For safety reason, return 99% of available return mul(_totalAvailableDai, 99) / 100; } function joinDai(address urn, uint256 amount) internal { DaiJoinLike daiJoin = DaiJoinLike(mcdDaiJoin); // Transfer Dai from strategy or pool to here IERC20(DAI).safeTransferFrom(msg.sender, address(this), amount); // Approves adapter to move dai. IERC20(DAI).safeApprove(mcdDaiJoin, 0); IERC20(DAI).safeApprove(mcdDaiJoin, amount); // Joins DAI into the vat daiJoin.join(urn, amount); } function joinGem(address adapter, uint256 amount) internal returns (uint256) { GemJoinLike gemJoin = GemJoinLike(adapter); IERC20 token = IERC20(gemJoin.gem()); // Transfer token from strategy or pool to here token.safeTransferFrom(msg.sender, address(this), amount); // Approves adapter to take the Gem amount token.safeApprove(adapter, 0); token.safeApprove(adapter, amount); // Joins Gem collateral into the vat gemJoin.join(address(this), amount); // Convert amount to 18 decimal return convertTo18(gemJoin.dec(), amount); } /** * @dev Get borrow dai amount. */ function _getBorrowAmount( address vat, address urn, uint256 vaultNum, uint256 wad ) internal returns (int256 amount) { // Updates stability fee rate uint256 rate = JugLike(mcdJug).drip(vaultType[vaultNum]); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed amt so together with the existing dai in the vat is enough to exit wad amount of DAI tokens amount = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra amt wei (for the given DAI wad amount) amount = mul(uint256(amount), rate) < mul(wad, RAY) ? amount + 1 : amount; } } /** * @dev Get collateral ratio */ function getCollateralRatio( uint256 collateralLocked, uint256 collateralRate, uint256 daiDebt ) internal pure returns (uint256) { if (collateralLocked == 0) { return 0; } if (daiDebt == 0) { return MAX_UINT_VALUE; } require(collateralRate != 0, "Collateral rate is zero"); return wdiv(wmul(collateralLocked, collateralRate), daiDebt); } /** * @dev Get Vault Debt Amount. */ function _getVaultDebt( bytes32 ilk, address urn, address vat ) internal view returns (uint256 wad) { // Get normalised debt [wad] (, uint256 art) = VatLike(vat).urns(ilk, urn); // Get stable coin rate [ray] (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Get balance from vat [rad] uint256 dai = VatLike(vat).dai(urn); wad = _getVaultDebt(art, rate, dai); } function _getVaultDebt( uint256 art, uint256 rate, uint256 dai ) internal pure returns (uint256 wad) { if (dai < mul(art, rate)) { uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; wad = mul(wad, RAY) < rad ? wad + 1 : wad; } else { wad = 0; } } function _getVaultInfo(uint256 vaultNum) internal view returns ( uint256 collateralLocked, uint256 collateralUsdRate, uint256 daiDebt, uint256 minimumDebt ) { address urn = ManagerLike(mcdManager).urns(vaultNum); address vat = ManagerLike(mcdManager).vat(); bytes32 ilk = vaultType[vaultNum]; // Get minimum liquidation ratio [ray] (, uint256 mat) = SpotterLike(mcdSpot).ilks(ilk); // Get collateral locked and normalised debt [wad] [wad] (uint256 ink, uint256 art) = VatLike(vat).urns(ilk, urn); // Get stable coin and collateral rate and min debt [ray] [ray] [rad] (, uint256 rate, uint256 spot, , uint256 dust) = VatLike(vat).ilks(ilk); // Get balance from vat [rad] collateralLocked = ink; daiDebt = _getVaultDebt(art, rate, VatLike(vat).dai(urn)); minimumDebt = dust / RAY; // Calculate collateral rate in 18 decimals collateralUsdRate = rmul(mat, spot) / 10**9; } /** * @dev Get Payback amount. * @notice We need to fetch latest art, rate and dai to calcualte payback amount. */ function _getWipeAmount( bytes32 ilk, address urn, address vat ) internal view returns (int256 amount) { // Get normalize debt, rate and dai balance from Vat (, uint256 art) = VatLike(vat).urns(ilk, urn); (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); uint256 dai = VatLike(vat).dai(urn); // Uses the whole dai balance in the vat to reduce the debt amount = toInt(dai / rate); // Checks the calculated amt is not higher than urn.art (total debt), otherwise uses its value amount = uint256(amount) <= art ? -amount : -toInt(art); } }
Store vault info. vaultNum Vault number. collateralType Collateral type of vault./
function registerVault(uint256 vaultNum, bytes32 collateralType) external override { require(msg.sender == ManagerLike(mcdManager).owns(vaultNum), "Not a vault owner"); vaultOwner[vaultNum] = msg.sender; vaultType[vaultNum] = collateralType; }
2,352,489
./full_match/1/0x728B035c6AfFAFA0a78dFCfeEfb68B20cc085046/sources/UniswapFlashSwapper.sol
This is the code that is executed after `simpleFlashLoan` initiated the flash-borrow When this code executes, this contract will hold the flash-borrowed _amount of _tokenBorrow unwrap WETH if necessary wrap the ETH if necessary
function simpleFlashLoanExecute( address _tokenBorrow, uint _amount, address _pairAddress, bool _isBorrowingEth, bool _isPayingEth, bytes memory _userData ) private { if (_isBorrowingEth) { IWETH(WETH).withdraw(_amount); } uint amountToRepay = _amount + fee; address tokenBorrowed = _isBorrowingEth ? ETH : _tokenBorrow; address tokenToRepay = _isPayingEth ? ETH : _tokenBorrow; execute(tokenBorrowed, _amount, tokenToRepay, amountToRepay, _userData); if (_isPayingEth) { } IERC20(_tokenBorrow).approve(_pairAddress, amountToRepay); }
2,970,558
./full_match/420/0xbDfF8fb43688fB4D2184DF8029A7238ac1413A24/sources/contracts/thirdweb-wallet/Wallet.sol
Performs a call; sends native tokens or calls a smart contract.
function _call(TransactionParams memory txParams) internal returns (bool) { txParams.data ); if (!success) { assembly { revert(add(result, 32), mload(result)) } } return success; }
13,225,911
./full_match/1/0x83C3c1E2Be5eD9463Bbb73DCF8b33C50000afce7/sources/contracts/LisaCrowdsaleSimple.sol
Claim the AT tokens. Can only be called by a participant or a seller. Transfers the AT tokens to the caller./
function claimTokens() external virtual nonReentrant returns (uint256) { require( status() == CrowdsaleStatus.SUCCESSFUL, "Crowdsale should be successful to claim tokens" ); uint256 amountAT = getAllocationFor(_msgSender()); if (amountAT > 0) { allocationsBT[_msgSender()] = 0; emit TokensClaimed(_msgSender(), amountAT); tokenAT.safeTransfer(_msgSender(), amountAT); } return amountAT; }
3,173,823
pragma solidity ^0.4.18; /** * @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) { // 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; } 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); uint256 c = _a - _b; return c; } /** * @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; } } /** * @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; address internal newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; newOwner = address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /* * @dev Change the owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } /* * @dev Accept the ownership. */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, Pausable { using SafeMath for uint256; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 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 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 whenNotPaused 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 whenNotPaused 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 whenNotPaused 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 whenNotPaused 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 whenNotPaused 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 whenNotPaused 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 Decrease the amount of tokens that an owner allowed to a spender by spender self. * approve should be called when allowed[msg.sender] == 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 _from The address which will transfer the funds from. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function spenderDecreaseApproval(address _from, uint256 _subtractedValue) public whenNotPaused returns (bool) { uint256 oldValue = allowed[_from][msg.sender]; if (_subtractedValue >= oldValue) { allowed[_from][msg.sender] = 0; } else { allowed[_from][msg.sender] = oldValue.sub(_subtractedValue); } emit Approval(_from, msg.sender, allowed[_from][msg.sender]); return true; } } /** * @title BCL token. * @dev Issued by blockchainlock.io */ contract BCLToken is StandardToken { string public name = "Blockchainlock Token"; string public symbol = "BCL"; uint8 public decimals = 18; /** * @dev The BCLToken constructor */ constructor() public { totalSupply_ = 360 * (10**26); // 36 billions balances[msg.sender] = totalSupply_; // Give the creator all initial tokens } }
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); uint256 c = _a - _b; return c; }
5,945,177
pragma solidity ^0.8.0; //SPDX-License-Identifier: MIT /** * Thingdoms, 2021. * Scotland, UK. */ import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; contract Thingdoms is ERC721Upgradeable, OwnableUpgradeable { using Counters for Counters.Counter; uint256 public constant THING_PRICE = 0.1 ether; uint8 public constant MAX_PUBLIC_MINTS = 5; uint8 public constant MAX_ALLOWLIST_MINTS = 2; uint16 public MAX_THINGS; uint16 public reservedTokens; bool public saleIsActive; bool public allowListSaleIsActive; bytes32 public merkleRoot; string private baseURI; /* * Creates a map of key: address, value: number allowed to mint */ mapping(address => uint8) private _userMints; Counters.Counter public tokenSupply; uint256[] private _allTokens; function initialize( string calldata collectionName, string calldata tokenName, uint16 maxNumber, bytes32 _merkleRoot ) public initializer { __ERC721_init(collectionName, tokenName); __Ownable_init(); baseURI = "https://thingdoms-server.herokuapp.com/pre-reveal-metadata/"; reservedTokens = 360; saleIsActive = false; allowListSaleIsActive = false; merkleRoot = _merkleRoot; MAX_THINGS = maxNumber; } /* * Sets the baseURI for all tokens metadata */ function setBaseURI(string calldata newBaseURI) external onlyOwner { baseURI = newBaseURI; } /* * Getter for the baseURI */ function _baseURI() internal view override returns (string memory) { return baseURI; } /* * Returns total number of existing tokens. Only used in test */ function totalSupply() public view returns (uint256) { return tokenSupply.current(); } function tokenByIndex(uint256 index) public view returns (uint256) { require( index < _allTokens.length, "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /* * Set the number of reserved tokens */ function setReservedTokens(uint16 reservedNumber) external onlyOwner { require( reservedNumber <= MAX_THINGS - tokenSupply.current(), "Not enough things left to reserve that amount" ); reservedTokens = reservedNumber; } /* * Start the allow list sale */ function startAllowListSale() external onlyOwner { require( allowListSaleIsActive == false, "Allow list sale already started" ); allowListSaleIsActive = true; } /* * Pause the allow list sale */ function pauseAllowListSale() external onlyOwner { require( allowListSaleIsActive == true, "Allow list sale already paused" ); allowListSaleIsActive = false; } /* * Start the general sale */ function startSale() external onlyOwner { require(saleIsActive == false, "Sale already started"); saleIsActive = true; } /* * Pause the general sale */ function pauseSale() external onlyOwner { require(saleIsActive == true, "Sale already paused"); saleIsActive = false; } /* * Get the number of already minted tokens for an address on the whitelist */ function getMintsForAddress(address _address) external view onlyOwner returns (uint8) { return _userMints[_address]; } /* * Mints tokens to the allowList users */ function mintAllowList(uint8 numberOfTokens, bytes32[] calldata proof) external payable { uint256 supply = tokenSupply.current(); require(allowListSaleIsActive, "Allow list sale is not active"); require( _userMints[msg.sender] + numberOfTokens <= MAX_ALLOWLIST_MINTS, "Exceeded mints per allowList user" ); require( THING_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct" ); require(isWhitelisted(msg.sender, proof), "Invalid proof"); _userMints[msg.sender] += numberOfTokens; for (uint8 i = 1; i <= numberOfTokens; i++) { tokenSupply.increment(); _allTokens.push(supply + i); _safeMint(msg.sender, supply + i); } } /* * Mints a given number of tokens */ function mint(uint8 numberOfTokens) external payable { uint256 supply = tokenSupply.current(); require(saleIsActive, "Sale is not active"); require( _userMints[msg.sender] + numberOfTokens <= MAX_PUBLIC_MINTS, "Exceeded mints per user" ); require( supply + numberOfTokens <= MAX_THINGS, "Not enough things left" ); require( THING_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct" ); _userMints[msg.sender] += numberOfTokens; for (uint8 i = 1; i <= numberOfTokens; i++) { tokenSupply.increment(); _allTokens.push(supply + i); _safeMint(msg.sender, supply + i); } } /** * Give away a number of tokens from the reserved amount to an address */ function giveAway(address _to, uint16 _amount) external onlyOwner { require(_amount <= reservedTokens, "Exceeds reserved Thing supply"); uint256 supply = tokenSupply.current(); for (uint16 i = 1; i <= _amount; i++) { tokenSupply.increment(); _allTokens.push(supply + i); // supply + i is the TOKEN_ID _safeMint(_to, supply + i); } reservedTokens -= _amount; } function setMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; } function isWhitelisted(address address_, bytes32[] memory proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(address_)); for (uint256 i = 0; i < proof.length; i++) { leaf = leaf <= proof[i] ? keccak256(abi.encodePacked(leaf, proof[i])) : keccak256(abi.encodePacked(proof[i], leaf)); } return leaf == merkleRoot; } /* * Withdraw the money from the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT 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.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 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.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 "../../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; /** * @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 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; /** * @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; } } // 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); }
Mints tokens to the allowList users/
function mintAllowList(uint8 numberOfTokens, bytes32[] calldata proof) external payable { uint256 supply = tokenSupply.current(); require(allowListSaleIsActive, "Allow list sale is not active"); require( _userMints[msg.sender] + numberOfTokens <= MAX_ALLOWLIST_MINTS, "Exceeded mints per allowList user" ); require( THING_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct" ); require(isWhitelisted(msg.sender, proof), "Invalid proof"); _userMints[msg.sender] += numberOfTokens; for (uint8 i = 1; i <= numberOfTokens; i++) { tokenSupply.increment(); _allTokens.push(supply + i); _safeMint(msg.sender, supply + i); } }
13,542,343
pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; // ------------------------------------------------------------------------ // Math library // ------------------------------------------------------------------------ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256){ uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ------------------------------------------------------------------------ // Basic token interface // ------------------------------------------------------------------------ contract IERC20 { uint256 public totalSupply; address public burnAddress = 0x0000000000000000000000000000000000000000; function balanceOf(address who) view public returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Minted(address target, uint256 mintedAmount); event Burned(address burner, uint256 burnedAmount); } // ------------------------------------------------------------------------ // Implementation of basic token interface // ------------------------------------------------------------------------ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) public balances; // ------------------------------------------------------------------------ // Get balance of user // ------------------------------------------------------------------------ function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer tokens // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Create tokens by adding to total supply and crediting the admin/owner // ------------------------------------------------------------------------ function mintToken(address _target, uint256 _mintedAmount) public returns(bool){ balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); emit Minted(_target, _mintedAmount); emit Transfer(address(0), address(this), _mintedAmount); emit Transfer(address(this), _target, _mintedAmount); return true; } // ------------------------------------------------------------------------ // Burn token by sending to to burn address & removing it from total supply // ------------------------------------------------------------------------ function burn(uint256 _burnAmount) public { address burner = msg.sender; balances[burner] = balances[burner].sub(_burnAmount); totalSupply = totalSupply.sub(_burnAmount); emit Burned(burner, _burnAmount); emit Transfer(burner, burnAddress, _burnAmount); } } // ------------------------------------------------------------------------ // Ownable contract definition // This is to allow for admin specific functions // ------------------------------------------------------------------------ contract Ownable { address payable public owner; address payable public potentialNewOwner; event OwnershipTransferred(address payable indexed _from, address payable indexed _to); // ------------------------------------------------------------------------ // Upon creation we set the creator as the owner // ------------------------------------------------------------------------ constructor() public { owner = msg.sender; } // ------------------------------------------------------------------------ // Set up the modifier to only allow the owner to pass through the condition // ------------------------------------------------------------------------ modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Transfer ownership to another user // ------------------------------------------------------------------------ function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; } // ------------------------------------------------------------------------ // To ensure correct transfer, the new owner has to confirm new ownership // ------------------------------------------------------------------------ function acceptOwnership() public { require(msg.sender == potentialNewOwner); emit OwnershipTransferred(owner, potentialNewOwner); owner = potentialNewOwner; } } // ------------------------------------------------------------------------ // Content moderatable contract definition // This is to allow for moderator specific functions // ------------------------------------------------------------------------ contract Moderatable is Ownable{ mapping(address => bool) public moderators; event ModeratorAdded(address indexed _moderator); event ModeratorRemoved(address indexed _moderator); // ------------------------------------------------------------------------ // Upon creation we set the first moderator as the owner // ------------------------------------------------------------------------ constructor() public { addModerator(owner); } // ------------------------------------------------------------------------ // Set up the modifier to only allow moderators to pass through the condition // ------------------------------------------------------------------------ modifier onlyModerators() { require(moderators[msg.sender] == true); _; } // ------------------------------------------------------------------------ // Add a moderator // ------------------------------------------------------------------------ function addModerator(address _newModerator) public onlyOwner { moderators[_newModerator] = true; emit ModeratorAdded(_newModerator); } // ------------------------------------------------------------------------ // Remove a moderator // ------------------------------------------------------------------------ function removeModerator(address _moderator) public onlyOwner { moderators[_moderator] = false; emit ModeratorRemoved(_moderator); } } // ------------------------------------------------------------------------ // Storage token definition // ------------------------------------------------------------------------ contract StorageToken is Moderatable{ struct Content{ address contentCreator; uint256 articleId; uint256 subArticleId; uint256 contentId; uint256 timestamp; string data; } Content[] public allContents; uint256[] public uniqueContentIds; mapping(uint256 => bool) public contentIdExists; mapping(uint256 => uint256[]) public articleIndexes; mapping(uint256 => uint256[]) public subArticleIndexes; mapping(uint256 => uint256[]) public contentIndexes; event ContentAdded(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp); event ContentAddedViaEvent(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp, string data); // ------------------------------------------------------------------------ // Add content to event for content persistance. // By storing the content in an event (compared to the experiment contract) // we get very cheap storage // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { emit ContentAddedViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content to struct for content persistance // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { allContents.push( Content(contentCreator, articleId, subArticleId, contentId, timestamp, data) ); uint256 id = allContents.length; articleIndexes[articleId].push(id); subArticleIndexes[subArticleId].push(id); contentIndexes[contentId].push(id); if(contentIdExists[contentId] == false){ uniqueContentIds.push(contentId); } contentIdExists[contentId] = true; emit ContentAdded(contentCreator, articleId, subArticleId, contentId, timestamp); } // ------------------------------------------------------------------------ // Get Content by from contents list by index (re-usable for below) // ------------------------------------------------------------------------ function getContentsFromIndexes(uint256[] memory contentIndexList) internal view returns(Content[] memory) { Content[] memory contents = new Content[](contentIndexList.length); for(uint256 i;i<contentIndexList.length;i++){ uint256 index = contentIndexList[i]; Content memory contentItem = allContents[index]; contents[i] = contentItem; } return contents; } // ------------------------------------------------------------------------ // Get Content by contentId // ------------------------------------------------------------------------ function getContentById(uint256 contentId) public view returns(Content[] memory) { uint256[] memory contentIndexList = contentIndexes[contentId]; return getContentsFromIndexes(contentIndexList); } // ------------------------------------------------------------------------ // Get all content ids // ------------------------------------------------------------------------ function getAllContentIds() public view returns(uint256[] memory) { return uniqueContentIds; } // ------------------------------------------------------------------------ // Get all content count // ------------------------------------------------------------------------ function getAllContentCount() public view returns(uint256) { return allContents.length; } // ------------------------------------------------------------------------ // Get unique content id count // ------------------------------------------------------------------------ function getUniqueContentIdCount() public view returns(uint256) { return uniqueContentIds.length; } // ------------------------------------------------------------------------ // Get all content ids for article // ------------------------------------------------------------------------ function getAllContentForArticle(uint256 articleId) public view returns(Content[] memory) { uint256[] memory contentIndexList = articleIndexes[articleId]; return getContentsFromIndexes(contentIndexList); } // ------------------------------------------------------------------------ // Count content for article // ------------------------------------------------------------------------ function countContentForArticle(uint256 articleId) public view returns(uint256 count) { return articleIndexes[articleId].length; } // ------------------------------------------------------------------------ // Get all content ids for sub-article // ------------------------------------------------------------------------ function getAllContentForSubArticle(uint256 subArticleId) public view returns(Content[] memory) { uint256[] memory contentIndexList = subArticleIndexes[subArticleId]; return getContentsFromIndexes(contentIndexList); } // ------------------------------------------------------------------------ // Count content for sub-article // ------------------------------------------------------------------------ function countContentForSubArticle(uint256 subArticleId) public view returns(uint256 count) { return subArticleIndexes[subArticleId].length; } } // ------------------------------------------------------------------------ // Morality token definition // ------------------------------------------------------------------------ contract Morality is ERC20, StorageToken { string public name; string public symbol; uint256 public decimals; address payable public creator; event LogFundsReceived(address sender, uint amount); event WithdrawLog(uint256 balanceBefore, uint256 amount, uint256 balanceAfter); event UpdatedTokenInformation(string newName, string newSymbol); // ------------------------------------------------------------------------ // Constructor to allow total tokens minted (upon creation) to be set // Name and Symbol can be changed via SetInfo (decided to remove from constructor) // ------------------------------------------------------------------------ constructor(uint256 _totalTokensToMint) payable public { name = "Morality"; symbol = "MO"; totalSupply = _totalTokensToMint; decimals = 18; balances[msg.sender] = totalSupply; creator = msg.sender; emit LogFundsReceived(msg.sender, msg.value); } // ------------------------------------------------------------------------ // Payable method allowing ether to be stored in the contract // ------------------------------------------------------------------------ function() payable external { emit LogFundsReceived(msg.sender, msg.value); } // ------------------------------------------------------------------------ // Transfer token (availabe to all) // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public returns (bool success){ return super.transfer(_to, _value); } // ------------------------------------------------------------------------ // Add content via event to event for content persistance (cheap) // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { super.addContentViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content for content persistance (expensive) // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { super.addContent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Update token information // ------------------------------------------------------------------------ function setTokenInformation(string memory _name, string memory _symbol) onlyOwner public { require(msg.sender != creator); name = _name; symbol = _symbol; emit UpdatedTokenInformation(name, symbol); } // ------------------------------------------------------------------------ // Withdraw ether from the contract // ------------------------------------------------------------------------ function withdraw(uint256 amount) onlyOwner public returns(bool){ require(amount <= address(this).balance); address(owner).transfer(amount); emit WithdrawLog(address(owner).balance.sub(amount), amount, address(owner).balance); return true; } // ------------------------------------------------------------------------ // Mint token // ------------------------------------------------------------------------ function mintToken(address target, uint256 mintedAmount) onlyOwner public returns (bool){ return super.mintToken(target, mintedAmount); } // ------------------------------------------------------------------------ // Burn token (send to burn address) // ------------------------------------------------------------------------ function burn(uint256 burnAmount) onlyOwner public{ return super.burn(burnAmount); } // ------------------------------------------------------------------------ // To remove contract from blockchain // ------------------------------------------------------------------------ function deprecateContract() onlyOwner public{ selfdestruct(creator); } }
------------------------------------------------------------------------ Get all content count ------------------------------------------------------------------------
function getAllContentCount() public view returns(uint256) { return allContents.length; }
12,751,451
// SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "../lib/AccessControl.sol"; import "../lib/SafeMath.sol"; interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address owner) external view returns (uint256); } interface IStrategy { function REINVEST_REWARD_BIPS() external view returns (uint256); function ADMIN_FEE_BIPS() external view returns (uint256); function DEV_FEE_BIPS() external view returns (uint256); function transferOwnership(address newOwner) external; function updateMinTokensToReinvest(uint256 newValue) external; function updateAdminFee(uint256 newValue) external; function updateDevFee(uint256 newValue) external; function updateDepositsEnabled(bool newValue) external; function updateMaxTokensToDepositWithoutReinvest(uint256 newValue) external; function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external; function updateReinvestReward(uint256 newValue) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function recoverAVAX(uint256 amount) external; function setAllowances() external; function revokeAllowance(address token, address spender) external; function allowDepositor(address depositor) external; function removeDepositor(address depositor) external; } /** * @notice Role-based manager for YakStrategy contracts * @dev YakStrategyManager may be used as `owner` on YakStrategy contracts */ contract YakStrategyManagerV1 is AccessControl { using SafeMath for uint256; uint256 public constant timelockLengthForOwnershipTransfer = 14 days; /// @notice Sets a global maximum for fee changes using bips (100 bips = 1%) uint256 public maxFeeBips = 1000; /// @notice Pending strategy owners (strategy => pending owner) mapping(address => address) public pendingOwners; /// @notice Earliest time pending owner can take effect (strategy => timestamp) mapping(address => uint256) public pendingOwnersTimelock; /// @notice Role to manage strategy owners bytes32 public constant STRATEGY_OWNER_SETTER_ROLE = keccak256("STRATEGY_OWNER_SETTER_ROLE"); /// @notice Role to initiate an emergency withdraw from strategies bytes32 public constant EMERGENCY_RESCUER_ROLE = keccak256("EMERGENCY_RESCUER_ROLE"); /// @notice Role to sweep funds from strategies bytes32 public constant EMERGENCY_SWEEPER_ROLE = keccak256("EMERGENCY_SWEEPER_ROLE"); /// @notice Role to manage global max fee configuration bytes32 public constant GLOBAL_MAX_FEE_SETTER_ROLE = keccak256("GLOBAL_MAX_FEE_SETTER_ROLE"); /// @notice Role to manage strategy fees and reinvest configurations bytes32 public constant FEE_SETTER_ROLE = keccak256("FEE_SETTER_ROLE"); /// @notice Role to allow/deny use of strategies bytes32 public constant STRATEGY_PERMISSIONER_ROLE = keccak256("STRATEGY_PERMISSIONER_ROLE"); /// @notice Role to disable deposits on strategies bytes32 public constant STRATEGY_DISABLER_ROLE = keccak256("STRATEGY_DISABLER_ROLE"); /// @notice Role to enable deposits on strategies bytes32 public constant STRATEGY_ENABLER_ROLE = keccak256("STRATEGY_ENABLER_ROLE"); event ProposeOwner(address indexed strategy, address indexed newOwner); event SetOwner(address indexed strategy, address indexed newValue); event SetFees(address indexed strategy, uint256 adminFeeBips, uint256 devFeeBips, uint256 reinvestFeeBips); event SetMinTokensToReinvest(address indexed strategy, uint256 newValue); event SetMaxTokensToDepositWithoutReinvest(address indexed strategy, uint256 newValue); event SetGlobalMaxFee(uint256 maxFeeBips, uint256 newMaxFeeBips); event SetDepositsEnabled(address indexed strategy, bool newValue); event SetAllowances(address indexed strategy); event Recover(address indexed strategy, address indexed token, uint256 amount); event Recovered(address token, uint amount); event EmergencyWithdraw(address indexed strategy); event AllowDepositor(address indexed strategy, address indexed depositor); event RemoveDepositor(address indexed strategy, address indexed depositor); constructor( address _manager, address _team, address _deployer ) { _setupRole(DEFAULT_ADMIN_ROLE, _manager); _setupRole(EMERGENCY_RESCUER_ROLE, _team); _setupRole(EMERGENCY_SWEEPER_ROLE, _deployer); _setupRole(GLOBAL_MAX_FEE_SETTER_ROLE, _team); _setupRole(FEE_SETTER_ROLE, _deployer); _setupRole(FEE_SETTER_ROLE, _team); _setupRole(STRATEGY_OWNER_SETTER_ROLE, _manager); _setupRole(STRATEGY_DISABLER_ROLE, _deployer); _setupRole(STRATEGY_DISABLER_ROLE, _team); _setupRole(STRATEGY_ENABLER_ROLE, _team); _setupRole(STRATEGY_PERMISSIONER_ROLE, _team); } receive() external payable {} /** * @notice Pass new value of `owner` through timelock * @dev Restricted to `STRATEGY_OWNER_SETTER_ROLE` to avoid griefing * @dev Resets timelock * @param strategy address * @param newOwner new value */ function proposeOwner(address strategy, address newOwner) external { require(hasRole(STRATEGY_OWNER_SETTER_ROLE, msg.sender), "proposeOwner::auth"); pendingOwnersTimelock[strategy] = block.timestamp + timelockLengthForOwnershipTransfer; pendingOwners[strategy] = newOwner; emit ProposeOwner(strategy, newOwner); } /** * @notice Set new value of `owner` and resets timelock * @dev This can be called by anyone * @param strategy address */ function setOwner(address strategy) external { require(pendingOwnersTimelock[strategy] != 0, "setOwner::not allowed"); require(pendingOwnersTimelock[strategy] <= block.timestamp, "setOwner::too soon"); IStrategy(strategy).transferOwnership(pendingOwners[strategy]); emit SetOwner(strategy, pendingOwners[strategy]); delete pendingOwners[strategy]; delete pendingOwnersTimelock[strategy]; } /** * @notice Set strategy fees * @dev Restricted to `FEE_SETTER_ROLE` and global max fee * @param strategy address * @param adminFeeBips deprecated * @param devFeeBips platform fees * @param reinvestRewardBips reinvest reward */ function setFees(address strategy, uint256 adminFeeBips, uint256 devFeeBips, uint256 reinvestRewardBips) external { require(hasRole(FEE_SETTER_ROLE, msg.sender), "setFees::auth"); require(adminFeeBips.add(devFeeBips).add(reinvestRewardBips) <= maxFeeBips, "setFees::Fees too high"); if (adminFeeBips != IStrategy(strategy).ADMIN_FEE_BIPS()){ IStrategy(strategy).updateAdminFee(adminFeeBips); } if (devFeeBips != IStrategy(strategy).DEV_FEE_BIPS()){ IStrategy(strategy).updateDevFee(devFeeBips); } if (reinvestRewardBips != IStrategy(strategy).REINVEST_REWARD_BIPS()){ IStrategy(strategy).updateReinvestReward(reinvestRewardBips); } emit SetFees(strategy, adminFeeBips, devFeeBips, reinvestRewardBips); } /** * @notice Set token approvals * @dev Restricted to `STRATEGY_ENABLER_ROLE` to avoid griefing * @param strategy address */ function setAllowances(address strategy) external { require(hasRole(STRATEGY_ENABLER_ROLE, msg.sender), "setAllowances::auth"); IStrategy(strategy).setAllowances(); emit SetAllowances(strategy); } /** * @notice Revoke token approvals * @dev Restricted to `STRATEGY_DISABLER_ROLE` to avoid griefing * @param strategy address * @param token address * @param spender address */ function revokeAllowance(address strategy, address token, address spender) external { require(hasRole(STRATEGY_DISABLER_ROLE, msg.sender) || hasRole(EMERGENCY_RESCUER_ROLE, msg.sender), "revokeAllowance::auth"); IStrategy(strategy).revokeAllowance(token, spender); } /** * @notice Set max strategy fees * @dev Restricted to `GLOBAL_MAX_FEE_SETTER_ROLE` * @param newMaxFeeBips max strategy fees */ function updateGlobalMaxFees(uint256 newMaxFeeBips) external { require(hasRole(GLOBAL_MAX_FEE_SETTER_ROLE, msg.sender), "updateGlobalMaxFees::auth"); emit SetGlobalMaxFee(maxFeeBips, newMaxFeeBips); maxFeeBips = newMaxFeeBips; } /** * @notice Permissioned function to set min tokens to reinvest * @dev Restricted to `FEE_SETTER_ROLE` * @param strategy address * @param newValue min tokens to reinvest */ function setMinTokensToReinvest(address strategy, uint256 newValue) external { require(hasRole(FEE_SETTER_ROLE, msg.sender), "setMinTokensToReinvest::auth"); IStrategy(strategy).updateMinTokensToReinvest(newValue); emit SetMinTokensToReinvest(strategy, newValue); } /** * @notice Permissioned function to set max tokens to deposit without reinvest * @dev Restricted to `FEE_SETTER_ROLE` * @param strategy address * @param newValue max tokens to deposit without reinvest */ function setMaxTokensToDepositWithoutReinvest(address strategy, uint256 newValue) external { require(hasRole(FEE_SETTER_ROLE, msg.sender), "setMaxTokensToDepositWithoutReinvest::auth"); IStrategy(strategy).updateMaxTokensToDepositWithoutReinvest(newValue); emit SetMaxTokensToDepositWithoutReinvest(strategy, newValue); } /** * @notice Permissioned function to enable deposits * @dev Restricted to `STRATEGY_ENABLER_ROLE` * @param strategy address */ function enableDeposits(address strategy) external { require(hasRole(STRATEGY_ENABLER_ROLE, msg.sender), "enableDeposits::auth"); IStrategy(strategy).updateDepositsEnabled(true); emit SetDepositsEnabled(strategy, true); } /** * @notice Permissioned function to disable deposits * @dev Restricted to `STRATEGY_DISABLER_ROLE` * @param strategy address */ function disableDeposits(address strategy) external { require(hasRole(STRATEGY_DISABLER_ROLE, msg.sender), "disableDeposits::auth"); IStrategy(strategy).updateDepositsEnabled(false); emit SetDepositsEnabled(strategy, false); } /** * @notice Permissioned function to add to list of allowed depositors * @dev Restricted to `STRATEGY_PERMISSIONER_ROLE` * @param strategy address * @param depositor address */ function allowDepositor(address strategy, address depositor) external { require(hasRole(STRATEGY_PERMISSIONER_ROLE, msg.sender), "allowDepositor::auth"); IStrategy(strategy).allowDepositor(depositor); emit AllowDepositor(strategy, depositor); } /** * @notice Permissioned function to remove from list of allowed depositors * @dev Restricted to `STRATEGY_PERMISSIONER_ROLE` * @param strategy address * @param depositor address */ function removeDepositor(address strategy, address depositor) external { require(hasRole(STRATEGY_PERMISSIONER_ROLE, msg.sender), "removeDepositor::auth"); IStrategy(strategy).removeDepositor(depositor); emit RemoveDepositor(strategy, depositor); } /** * @notice Permissioned function to recover deployed assets back into the strategy contract * @dev Restricted to `EMERGENCY_RESCUER_ROLE` * @dev Always passes `true` to disable deposits * @dev Rescued funds stay in strategy until recovered (see `recover*`) * @param strategy address * @param minReturnAmountAccepted amount */ function rescueDeployedFunds(address strategy, uint256 minReturnAmountAccepted) external { require(hasRole(EMERGENCY_RESCUER_ROLE, msg.sender), "rescueDeployedFunds::auth"); IStrategy(strategy).rescueDeployedFunds(minReturnAmountAccepted, true); emit EmergencyWithdraw(strategy); } /** * @notice Permissioned function to recover and transfer any token from strategy contract * @dev Restricted to `EMERGENCY_SWEEPER_ROLE` * @dev Intended for use in case of `rescueDeployedFunds` * @param strategy address * @param tokenAddress address * @param tokenAmount amount */ function recoverTokens(address strategy, address tokenAddress, uint256 tokenAmount) external { require(hasRole(EMERGENCY_SWEEPER_ROLE, msg.sender), "recoverTokens::auth"); IStrategy(strategy).recoverERC20(tokenAddress, tokenAmount); _transferTokens(tokenAddress, tokenAmount); emit Recover(strategy, tokenAddress, tokenAmount); } /** * @notice Permissioned function to transfer any token from this contract * @dev Restricted to `EMERGENCY_SWEEPER_ROLE` * @param tokenAddress token address * @param tokenAmount amount */ function sweepTokens(address tokenAddress, uint256 tokenAmount) external { require(hasRole(EMERGENCY_SWEEPER_ROLE, msg.sender), "sweepTokens::auth"); _transferTokens(tokenAddress, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /** * @notice Internal function to transfer tokens to msg.sender * @param tokenAddress token address * @param tokenAmount amount */ function _transferTokens(address tokenAddress, uint256 tokenAmount) internal { uint256 balance = IERC20(tokenAddress).balanceOf(address(this)); if (tokenAmount < balance) { tokenAmount = balance; } require(IERC20(tokenAddress).transfer(msg.sender, tokenAmount), "_transferTokens::transfer failed"); } /** * @notice Permissioned function to transfer AVAX from any strategy into this contract * @dev Restricted to `EMERGENCY_SWEEPER_ROLE` * @dev After recovery, contract may become gas-bound. * @dev Intended for use in case of `rescueDeployedFunds`, as deposit tokens will be locked in the strategy. * @param strategy address * @param amount amount */ function recoverAVAX(address strategy, uint256 amount) external { require(hasRole(EMERGENCY_SWEEPER_ROLE, msg.sender), "recoverAVAX::auth"); emit Recover(strategy, address(0), amount); IStrategy(strategy).recoverAVAX(amount); } /** * @notice Permissioned function to transfer AVAX from this contract * @dev Restricted to `EMERGENCY_SWEEPER_ROLE` * @param amount amount */ function sweepAVAX(uint256 amount) external { require(hasRole(EMERGENCY_SWEEPER_ROLE, msg.sender), "sweepAVAX::auth"); uint256 balance = address(this).balance; if (amount < balance) { amount = balance; } (bool success, ) = msg.sender.call{value: amount}(""); require(success == true, "recoverAVAX::transfer failed"); emit Recovered(address(0), amount); } }
Pass new value of `owner` through timelock Restricted to `STRATEGY_OWNER_SETTER_ROLE` to avoid griefing Resets timelock strategy address newOwner new value/
function proposeOwner(address strategy, address newOwner) external { require(hasRole(STRATEGY_OWNER_SETTER_ROLE, msg.sender), "proposeOwner::auth"); pendingOwnersTimelock[strategy] = block.timestamp + timelockLengthForOwnershipTransfer; pendingOwners[strategy] = newOwner; emit ProposeOwner(strategy, newOwner); }
5,417,790
./full_match/80001/0x9B81C4B3883264208aA845be47CcCbcBEA46D2d3/sources/contracts/BlocTaleFungibleItemsBase.sol
Lets an authorized address mint NFTs to a recipient. - The logic in the `_canMint` function determines whether the caller is authorized to mint NFTs. - If `_tokenId == type(uint256).max` a new NFT at tokenId `nextTokenIdToMint` is minted. If the given `tokenId < nextTokenIdToMint`, then additional supply of an existing NFT is being minted. _to The recipient of the NFTs to mint. _tokenId The tokenId of the NFT to mint. _amount The amount of the same NFT to mint./
function mintTo( address _to, uint256 _tokenId, uint256 _amount ) public virtual { require(_canMint(), "Not authorized to mint."); uint256 tokenIdToMint; uint256 nextIdToMint = nextTokenIdToMint(); if (_tokenId == type(uint256).max) { tokenIdToMint = nextIdToMint; nextTokenIdToMint_ += 1; require(_tokenId < nextIdToMint, "invalid id"); tokenIdToMint = _tokenId; } _mint(_to, tokenIdToMint, _amount, ""); }
5,594,802
/** *Submitted for verification at Etherscan.io on 2020-10-21 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "Keep3r::SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "Keep3r::SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "Keep3r::SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "Keep3r::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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { return mod(a, b, "Keep3r::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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } interface Governance { function proposeJob(address job) external returns (uint); } interface WETH9 { function deposit() external payable; function balanceOf(address account) external view returns (uint); function approve(address spender, uint amount) external returns (bool); } interface Uniswap { function factory() 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); } interface UniswapPair { function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function balanceOf(address account) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function totalSupply() external view returns (uint); } interface Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } interface Keep3rHelper { function getQuoteLimit(uint gasUsed) external view returns (uint); } contract Keep3r { using SafeMath for uint; /// @notice Keep3r Helper to set max prices for the ecosystem Keep3rHelper public KPRH; /// @notice WETH address to liquidity into UNI WETH9 public constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice UniswapV2Router address Uniswap public constant UNI = Uniswap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /// @notice EIP-20 token name for this token string public constant name = "Keep3r"; /// @notice EIP-20 token symbol for this token string public constant symbol = "KPR"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @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; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint 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,uint nonce,uint 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,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @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, uint nonce, uint 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), "::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "::delegateBySig: invalid nonce"); require(now <= expiry, "::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint delegatorBalance = bonds[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed job, address indexed keeper, uint block); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); /// @notice 1 day to bond to become a keeper uint constant public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint constant public UNBOND = 14 days; /// @notice 7 days maximum downtime before being slashed uint constant public DOWNTIME = 7 days; /// @notice 3 days till liquidity can be bound uint constant public LIQUIDITYBOND = 3 days; /// @notice 5% of funds slashed for downtime uint constant public DOWNTIMESLASH = 500; uint constant public BASE = 10000; /// @notice tracks all current bondings (time) mapping(address => uint) public bondings; /// @notice tracks all current unbondings (time) mapping(address => uint) public unbondings; /// @notice allows for partial unbonding mapping(address => uint) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => uint) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => uint) public bonds; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the amount of job executions for a keeper mapping(address => uint) public work; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => uint) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @notice job proposal delay mapping(address => uint) public jobProposalDelay; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal gasUsed; constructor() public { // Set governance for this token governance = msg.sender; _mint(msg.sender, 10000e18); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external { require(msg.sender == governance, "Keep3r::approveLiquidity: governance only"); require(!liquidityAccepted[liquidity], "Keep3r::approveLiquidity: existing liquidity pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external { require(msg.sender == governance, "Keep3r::revokeLiquidity: governance only"); liquidityAccepted[liquidity] = false; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Allows liquidity providers to submit jobs * @param amount the amount of tokens to mint to treasury * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external { require(liquidityAccepted[liquidity], "Keep3r::addLiquidityToJob: asset not accepted as liquidity"); UniswapPair(liquidity).transferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay[job] < now) { Governance(governance).proposeJob(job); jobProposalDelay[job] = now.add(UNBOND); } emit SubmitJob(job, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "Keep3r::addLiquidityToJob: asset not accepted as liquidity"); require(liquidityApplied[provider][liquidity][job] != 0, "Keep3r::credit: submitJob first"); require(liquidityApplied[provider][liquidity][job] < now, "Keep3r::credit: still bonding"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(liquidityAmount[msg.sender][liquidity][job]).div(UniswapPair(liquidity).totalSupply()); credits[job] = credits[job].add(_credit); liquidityAmount[msg.sender][liquidity][job] = 0; emit ApplyCredit(job, msg.sender, block.number, _credit); } /** * @notice Unbond liquidity for a pending keeper job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "Keep3r::credit: pending credit, settle first"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "Keep3r::unbondLiquidityFromJob: insufficient funds"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(amount).div(UniswapPair(liquidity).totalSupply()); if (_credit > credits[job]) { credits[job] = 0; } else { credits[job].sub(_credit); } emit UnbondJob(job, msg.sender, block.number, liquidityProvided[msg.sender][liquidity][job]); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "Keep3r::removeJob: unbond first"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "Keep3r::removeJob: still unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; UniswapPair(liquidity).transfer(msg.sender, _amount); emit RemoveJob(job, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external { require(msg.sender == governance, "Keep3r::mint: governance only"); _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "::_burn: burn from the zero address"); balances[dst] = balances[dst].sub(amount, "::_burn: burn amount exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performend work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) external { require(jobs[msg.sender], "Keep3r::workReceipt: only jobs can approve work"); gasUsed = gasUsed.sub(gasleft()); require(amount < KPRH.getQuoteLimit(gasUsed), "Keep3r::workReceipt: spending over max limit"); credits[msg.sender] = credits[msg.sender].sub(amount, "Keep3r::workReceipt: insuffient funds to pay keeper"); lastJob[keeper] = now; _mint(address(this), amount); _bond(keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(msg.sender, keeper, block.number); } function _bond(address _from, uint _amount) internal { bonds[_from] = bonds[_from].add(_amount); totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } function _unbond(address _from, uint _amount) internal { bonds[_from] = bonds[_from].sub(_amount); totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external { require(msg.sender == governance, "Keep3r::addJob: only governance can add jobs"); require(!jobs[job], "Keep3r::addJob: job already known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external { require(msg.sender == governance, "Keep3r::removeJob: only governance can remove jobs"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(Keep3rHelper _kprh) external { require(msg.sender == governance, "Keep3r::setKeep3rHelper: only governance can set"); KPRH = _kprh; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "Keep3r::setGovernance: only governance can set"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "Keep3r::acceptGovernance: only pendingGovernance can accept"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @return true/false if the address is a keeper */ function isKeeper(address keeper) external returns (bool) { gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { gasUsed = gasleft(); return keepers[keeper] && bonds[keeper] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper */ function bond(uint amount) external { require(pendingbonds[msg.sender] == 0, "Keep3r::bond: current pending bond"); require(!blacklist[msg.sender], "Keep3r::bond: keeper is blacklisted"); bondings[msg.sender] = now.add(BOND); _transferTokens(msg.sender, address(this), amount); pendingbonds[msg.sender] = pendingbonds[msg.sender].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender], amount); } function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice allows a keeper to activate/register themselves after bonding */ function activate() external { require(!blacklist[msg.sender], "Keep3r::activate: keeper is blacklisted"); require(bondings[msg.sender] != 0 && bondings[msg.sender] < now, "Keep3r::activate: still bonding"); if (firstSeen[msg.sender] == 0) { firstSeen[msg.sender] = now; keeperList.push(msg.sender); lastJob[msg.sender] = now; } keepers[msg.sender] = true; _bond(msg.sender, pendingbonds[msg.sender]); pendingbonds[msg.sender] = 0; emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender]); } /** * @notice begin the unbonding process to stop being a keeper * @param amount allows for partial unbonding */ function unbond(uint amount) external { unbondings[msg.sender] = now.add(UNBOND); _unbond(msg.sender, amount); partialUnbonding[msg.sender] = partialUnbonding[msg.sender].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender], amount); } /** * @notice withdraw funds after unbonding has finished */ function withdraw() external { require(unbondings[msg.sender] != 0 && unbondings[msg.sender] < now, "Keep3r::withdraw: still unbonding"); require(!disputes[msg.sender], "Keep3r::withdraw: pending disputes"); _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender]); emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender]); partialUnbonding[msg.sender] = 0; } /** * @notice slash a keeper for downtime * @param keeper the address being slashed */ function down(address keeper) external { require(keepers[msg.sender], "Keep3r::down: not a keeper"); require(keepers[keeper], "Keep3r::down: keeper not registered"); require(lastJob[keeper].add(DOWNTIME) < now, "Keep3r::down: keeper safe"); uint _slash = bonds[keeper].mul(DOWNTIMESLASH).div(BASE); _unbond(keeper, _slash); _bond(msg.sender, _slash); lastJob[keeper] = now; lastJob[msg.sender] = now; emit KeeperSlashed(keeper, msg.sender, block.number, _slash); } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external returns (uint) { require(msg.sender == governance, "Keep3r::dispute: only governance can dispute"); disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address keeper, uint amount) public { require(msg.sender == governance, "Keep3r::slash: only governance can resolve"); _transferTokens(address(this), governance, amount); _unbond(keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external { require(msg.sender == governance, "Keep3r::slash: only governance can resolve"); keepers[keeper] = false; blacklist[keeper] = true; slash(keeper, bonds[keeper]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external { require(msg.sender == governance, "Keep3r::resolve: only governance can resolve"); disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @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 (uint) { 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 amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { 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 amount 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, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "::permit: invalid signature"); require(signatory == owner, "::permit: unauthorized"); require(now <= deadline, "::permit: 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 (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _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 amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "::_transferTokens: cannot transfer to the zero address"); balances[src] = balances[src].sub(amount, "::_transferTokens: transfer amount exceeds balance"); balances[dst] = balances[dst].add(amount, "::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); } function getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
Allows governance to remove a job from the systems job address of the contract for which work should be performed/
function removeJob(address job) external { require(msg.sender == governance, "Keep3r::removeJob: only governance can remove jobs"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); }
603,489
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SafeMath { function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB906(a, b, "SafeMath: subtraction overflow"); } function SUB906(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 MUL601(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 DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV456(a, b, "SafeMath: division by zero"); } function DIV456(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD78(a, b, "SafeMath: modulo by zero"); } function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA207() 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; } } interface IERC20 { function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/utils/Address.sol library Address { function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE944(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL15(target, data, "Address: low-level call failed"); } function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT600(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: contracts/token/ERC20/ERC20.sol 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(_MSGSENDER877(), recipient, amount); return true; } function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, amount); return true; } function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(sender, recipient, amount); _APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue)); return true; } function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER67(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER81(sender, recipient, amount); _balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD388(amount); emit TRANSFER657(sender, recipient, amount); } function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER81(address(0), account, amount); _totalSupply = _totalSupply.ADD388(amount); _balances[account] = _balances[account].ADD388(amount); emit TRANSFER657(address(0), account, amount); } function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER81(account, address(0), amount); _balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB906(amount); emit TRANSFER657(account, address(0), amount); } function _APPROVE455(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL956(owner, spender, amount); } function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value)); } function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value)); } function SAFEAPPROVE284(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE35(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value)); } function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN31(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).FUNCTIONCALL15(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IVault is IERC20 { function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING function EARN763() external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING function DEPOSITALL187() external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL63() external; //inject NONSTANDARD NAMING function DISTRIBUTE67() external; //inject NONSTANDARD NAMING function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_2 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[2] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurve3Pool { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[3] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_4 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveZap_4 { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING external returns (uint256); function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function CURVE335() external returns (address); //inject NONSTANDARD NAMING function TOKEN190() external returns (address); //inject NONSTANDARD NAMING } interface ICurveZap { function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveMintr { function MINT951(address) external; //inject NONSTANDARD NAMING function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveVotingEscrow { function LOCKED178(address arg0) //inject NONSTANDARD NAMING external view returns (int128 amount, uint256 end); function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING function WITHDRAW593() external; //inject NONSTANDARD NAMING function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING } interface ICurveSmartContractChecker { function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING } interface UniswapRouterV2 { function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function ADDLIQUIDITY947( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event APPROVAL956( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING external view returns (uint256); function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531( //inject NONSTANDARD NAMING address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT326( //inject NONSTANDARD NAMING address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING event BURN673( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event SWAP227( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES964() //inject NONSTANDARD NAMING external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING function BURN57(address to) //inject NONSTANDARD NAMING external returns (uint256 amount0, uint256 amount1); function SWAP519( //inject NONSTANDARD NAMING uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function SKIM366(address to) external; //inject NONSTANDARD NAMING function SYNC84() external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED988( //inject NONSTANDARD NAMING address indexed token0, address indexed token1, address pair, uint256 ); function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING external view returns (address pair); function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING function FEETO341() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING external returns (address pair); } interface ICurveTBTC { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 min_mint_amount ) external returns (uint256); } interface IKeepRewardsClaimable { function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING } // Base of all strategy contracts abstract contract VoxStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees uint256 public treasuryFee = 1000; uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING uint256 public strategyFee = 500; uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING uint256 public developerFee = 250; uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING // Withdrawal fee uint256 public withdrawalFee = 15; uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING // Tokens address public underlying; address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING // User accounts address public governance; address public strategist; address public treasury; address public devfund; address public timelock; address public vault; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public { require(_underlying != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_treasury != address(0)); require(_devfund != address(0)); require(_timelock != address(0)); require(_vault != address(0)); underlying = _underlying; governance = _governance; strategist = _strategist; treasury = _treasury; devfund = _devfund; timelock = _timelock; vault = _vault; } // **** Modifiers **** // modifier RESTRICTED912 { //inject NONSTANDARD NAMING require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(underlying).BALANCEOF68(address(this)); } function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881()); } function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING // **** Setters **** // function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); treasuryFee = _treasuryFee; } function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); strategyFee = _strategyFee; } function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); developerFee = _developerFee; } function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); withdrawalFee = _withdrawalFee; } function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); treasury = _treasury; } function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING require(msg.sender == devfund, "!devfund"); devfund = _devfund; } function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); timelock = _timelock; } // **** State mutations **** // function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING // Governance only function to salvage non-underlying assets function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); require(underlying != address(_asset), "underlying"); balance = _asset.BALANCEOF68(address(this)); _asset.SAFETRANSFER331(treasury, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == vault, "!vault"); uint256 _balance = IERC20(underlying).BALANCEOF68(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME235(_amount.SUB906(_balance)); _amount = _amount.ADD388(_balance); } uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605); IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee)); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING _WITHDRAWALL78(); balance = IERC20(underlying).BALANCEOF68(address(this)); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, balance); } function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING _WITHDRAWSOME235(BALANCEOFPOOL881()); } function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING function HARVEST372() public virtual; //inject NONSTANDARD NAMING function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { // Treasury fees IERC20(underlying).SAFETRANSFER331( treasury, _underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971) ); // Strategy fee IERC20(underlying).SAFETRANSFER331( strategist, _underlying.MUL601(strategyFee).DIV456(strategyfeebase640) ); // Developer fee IERC20(underlying).SAFETRANSFER331( devfund, _underlying.MUL601(developerFee).DIV456(developerfeebase561) ); DEPOSIT115(); } } // **** Emergency functions **** function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _SWAPUNISWAP503( //inject NONSTANDARD NAMING address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).SAFEAPPROVE284(univ2Router2, 0); IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount); address[] memory path; if (_from == weth339 || _to == weth339) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth339; path[2] = _to; } UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167( _amount, 0, path, address(this), now.ADD388(60) ); } } // Base contract for Curve based vault strategies abstract contract VoxStrategyCurveBase is VoxStrategyBase { // curve dao address public curve; address public gauge; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // keep address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC; address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault) { curve = _curve; gauge = _gauge; } // **** Getters **** function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).BALANCEOF68(address(this)); } function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this)); } function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING // **** Setters **** function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function DEPOSIT115() public override { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { IERC20(underlying).SAFEAPPROVE284(gauge, 0); IERC20(underlying).SAFEAPPROVE284(gauge, _underlying); ICurveGauge(gauge).DEPOSIT115(_underlying); } } function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING internal override returns (uint256) { ICurveGauge(gauge).WITHDRAW593(_amount); return _amount; } } contract VoxStrategyCurveTBTC is VoxStrategyCurveBase { // Curve stuff address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c; address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd; // EVENTS event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING constructor( address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyCurveBase( tbtc_pool, tbtc_gauge, tbtc_crv, _governance, _strategist, _treasury, _devfund, _timelock, _vault ) {} // **** Views **** function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING public override view returns (address, uint256) { return (wbtc162, 2); } function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING return "VoxStrategyCurveTBTC"; } // **** State Mutations **** function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING // bitcoin we want to convert to (address to, uint256 toIndex) = GETMOSTPREMIUM814(); // Collects crv tokens // this also sends KEEP to keep_rewards contract ICurveMintr(mintr).MINT951(gauge); uint256 _crv = IERC20(crv).BALANCEOF68(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).SAFETRANSFER331( treasury, _keepCRV ); } _crv = _crv.SUB906(_keepCRV); _SWAPUNISWAP503(crv, to, _crv); } // Collects keep tokens IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536(); uint256 _keep = IERC20(keep).BALANCEOF68(address(this)); if (_keep > 0) { _SWAPUNISWAP503(keep, to, _keep); } // Adds liquidity to curve.fi's pool // to get back underlying (tbtccrv) uint256 _to = IERC20(to).BALANCEOF68(address(this)); if (_to > 0) { IERC20(to).SAFEAPPROVE284(curve, 0); IERC20(to).SAFEAPPROVE284(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0); } // Distribute the collected funds and deposit underlying // Emit harvested event _DISTRIBUTEANDDEPOSIT388(); emit HARVESTED180(to, _to); } }
inject NONSTANDARD NAMING
function _SETUPDECIMALS854(uint8 decimals_) internal {
12,568,908
// SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ERC165} from "@solidstate/contracts/introspection/ERC165.sol"; import {ERC1155Enumerable} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IERC20Metadata} from "@solidstate/contracts/token/ERC20/metadata/IERC20Metadata.sol"; import {Multicall} from "@solidstate/contracts/utils/Multicall.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {PoolInternal} from "./PoolInternal.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolBase is PoolInternal, ERC1155Enumerable, ERC165, Multicall { constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 feePremium64x64, int128 feeApy64x64 ) PoolInternal( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, feePremium64x64, feeApy64x64 ) {} /** * @notice see IPoolBase; inheritance not possible due to linearization issues */ function name() external view returns (string memory) { PoolStorage.Layout storage l = PoolStorage.layout(); return string( abi.encodePacked( IERC20Metadata(l.underlying).symbol(), " / ", IERC20Metadata(l.base).symbol(), " - Premia Options Pool" ) ); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(PoolInternal, ERC1155Enumerable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from './IERC165.sol'; import { ERC165Storage } from './ERC165Storage.sol'; /** * @title ERC165 implementation */ abstract contract ERC165 is IERC165 { using ERC165Storage for ERC165Storage.Layout; /** * @inheritdoc IERC165 */ function supportsInterface(bytes4 interfaceId) public view returns (bool) { return ERC165Storage.layout().isSupportedInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol'; import { IERC1155Enumerable } from './IERC1155Enumerable.sol'; import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol'; /** * @title ERC1155 implementation including enumerable and aggregate functions */ abstract contract ERC1155Enumerable is IERC1155Enumerable, ERC1155Base, ERC1155EnumerableInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @inheritdoc IERC1155Enumerable */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply(id); } /** * @inheritdoc IERC1155Enumerable */ function totalHolders(uint256 id) public view virtual returns (uint256) { return _totalHolders(id); } /** * @inheritdoc IERC1155Enumerable */ function accountsByToken(uint256 id) public view virtual returns (address[] memory) { return _accountsByToken(id); } /** * @inheritdoc IERC1155Enumerable */ function tokensByAccount(address account) public view virtual returns (uint256[] memory) { return _tokensByAccount(account); } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155EnumerableInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC20 metadata interface */ interface IERC20Metadata { /** * @notice return token name * @return token name */ function name() external view returns (string memory); /** * @notice return token symbol * @return token symbol */ function symbol() external view returns (string memory); /** * @notice return token decimals, generally used only for display purposes * @return token decimals */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IMulticall } from './IMulticall.sol'; /** * @title Utility contract for supporting processing of multiple function calls in a single transaction */ abstract contract Multicall is IMulticall { /** * @inheritdoc IMulticall */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); unchecked { for (uint256 i; i < data.length; i++) { (bool success, bytes memory returndata) = address(this) .delegatecall(data[i]); if (success) { results[i] = returndata; } else { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } return results; } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol"; import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; library PoolStorage { using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; enum TokenType { UNDERLYING_FREE_LIQ, BASE_FREE_LIQ, UNDERLYING_RESERVED_LIQ, BASE_RESERVED_LIQ, LONG_CALL, SHORT_CALL, LONG_PUT, SHORT_PUT } struct PoolSettings { address underlying; address base; address underlyingOracle; address baseOracle; } struct QuoteArgsInternal { address feePayer; // address of the fee payer uint64 maturity; // timestamp of option maturity int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price uint256 contractSize; // size of option contract bool isCall; // true for call, false for put } struct QuoteResultInternal { int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee) int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size } struct BatchData { uint256 eta; uint256 totalPendingDeposits; } bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool"); uint256 private constant C_DECAY_BUFFER = 12 hours; uint256 private constant C_DECAY_INTERVAL = 4 hours; struct Layout { // ERC20 token addresses address base; address underlying; // AggregatorV3Interface oracle addresses address baseOracle; address underlyingOracle; // token metadata uint8 underlyingDecimals; uint8 baseDecimals; // minimum amounts uint256 baseMinimum; uint256 underlyingMinimum; // deposit caps uint256 _deprecated_basePoolCap; uint256 _deprecated_underlyingPoolCap; // market state int128 _deprecated_steepness64x64; int128 cLevelBase64x64; int128 cLevelUnderlying64x64; uint256 cLevelBaseUpdatedAt; uint256 cLevelUnderlyingUpdatedAt; uint256 updatedAt; // User -> isCall -> depositedAt mapping(address => mapping(bool => uint256)) depositedAt; mapping(address => mapping(bool => uint256)) divestmentTimestamps; // doubly linked list of free liquidity intervals // isCall -> User -> User mapping(bool => mapping(address => address)) liquidityQueueAscending; mapping(bool => mapping(address => address)) liquidityQueueDescending; // minimum resolution price bucket => price mapping(uint256 => int128) bucketPrices64x64; // sequence id (minimum resolution price bucket / 256) => price update sequence mapping(uint256 => uint256) priceUpdateSequences; // isCall -> batch data mapping(bool => BatchData) nextDeposits; // user -> batch timestamp -> isCall -> pending amount mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits; EnumerableSet.UintSet tokenIds; // user -> isCallPool -> total value locked of user (Used for liquidity mining) mapping(address => mapping(bool => uint256)) userTVL; // isCallPool -> total value locked mapping(bool => uint256) totalTVL; // steepness values int128 steepnessBase64x64; int128 steepnessUnderlying64x64; // User -> isCallPool -> isBuybackEnabled mapping(address => mapping(bool => bool)) isBuybackEnabled; // LongTokenId -> averageC mapping(uint256 => int128) avgCLevel64x64; // APY fee tracking // underwriter -> shortTokenId -> amount mapping(address => mapping(uint256 => uint256)) feesReserved; // shortTokenId -> 64x64 fixed point representation of apy fee mapping(uint256 => int128) feeReserveRates; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice calculate ERC1155 token id for given option parameters * @param tokenType TokenType enum * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @return tokenId token id */ function formatTokenId( TokenType tokenType, uint64 maturity, int128 strike64x64 ) internal pure returns (uint256 tokenId) { tokenId = (uint256(tokenType) << 248) + (uint256(maturity) << 128) + uint256(int256(strike64x64)); } /** * @notice derive option maturity and strike price from ERC1155 token id * @param tokenId token id * @return tokenType TokenType enum * @return maturity timestamp of option maturity * @return strike64x64 option strike price */ function parseTokenId(uint256 tokenId) internal pure returns ( TokenType tokenType, uint64 maturity, int128 strike64x64 ) { assembly { tokenType := shr(248, tokenId) maturity := shr(128, tokenId) strike64x64 := tokenId } } function getTokenType(bool isCall, bool isLong) internal pure returns (TokenType tokenType) { if (isCall) { tokenType = isLong ? TokenType.LONG_CALL : TokenType.SHORT_CALL; } else { tokenType = isLong ? TokenType.LONG_PUT : TokenType.SHORT_PUT; } } function getPoolToken(Layout storage l, bool isCall) internal view returns (address token) { token = isCall ? l.underlying : l.base; } function getTokenDecimals(Layout storage l, bool isCall) internal view returns (uint8 decimals) { decimals = isCall ? l.underlyingDecimals : l.baseDecimals; } function getMinimumAmount(Layout storage l, bool isCall) internal view returns (uint256 minimumAmount) { minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum; } /** * @notice get the total supply of free liquidity tokens, minus pending deposits * @param l storage layout struct * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of total free liquidity */ function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall) internal view returns (int128) { uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); return ABDKMath64x64Token.fromDecimals( ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.totalPendingDeposits(isCall), l.getTokenDecimals(isCall) ); } function getReinvestmentStatus( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { uint256 timestamp = l.divestmentTimestamps[account][isCallPool]; return timestamp == 0 || timestamp > block.timestamp; } function addUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (_isInQueue(account, asc, desc)) return; address last = desc[address(0)]; asc[last] = account; desc[account] = last; desc[address(0)] = account; } function removeUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (!_isInQueue(account, asc, desc)) return; address prev = desc[account]; address next = asc[account]; asc[prev] = next; desc[next] = prev; delete asc[account]; delete desc[account]; } function isInQueue( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; return _isInQueue(account, asc, desc); } function _isInQueue( address account, mapping(address => address) storage asc, mapping(address => address) storage desc ) private view returns (bool) { return asc[account] != address(0) || desc[address(0)] == account; } /** * @notice get current C-Level, without accounting for pending adjustments * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getRawCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64; } /** * @notice get current C-Level, accounting for unrealized decay * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { // get raw C-Level from storage cLevel64x64 = l.getRawCLevel64x64(isCall); // account for C-Level decay cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall); } /** * @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits * @param l storage layout struct * @param isCall whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level * @return liquidity64x64 64x64 fixed point representation of new liquidity amount */ function getRealPoolState(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64, int128 liquidity64x64) { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); if ( batchData.totalPendingDeposits > 0 && batchData.eta != 0 && block.timestamp >= batchData.eta ) { liquidity64x64 = ABDKMath64x64Token .fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) .add(oldLiquidity64x64); cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, liquidity64x64, isCall ); } else { cLevel64x64 = oldCLevel64x64; liquidity64x64 = oldLiquidity64x64; } } /** * @notice calculate updated C-Level, accounting for unrealized decay * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay */ function applyCLevelDecayAdjustment( Layout storage l, int128 oldCLevel64x64, bool isCall ) internal view returns (int128 cLevel64x64) { uint256 timeElapsed = block.timestamp - (isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt); // do not apply C decay if less than 24 hours have elapsed if (timeElapsed > C_DECAY_BUFFER) { timeElapsed -= C_DECAY_BUFFER; } else { return oldCLevel64x64; } int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu( timeElapsed, C_DECAY_INTERVAL ); uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); uint256 tvl = l.totalTVL[isCall]; int128 utilization = ABDKMath64x64.divu( tvl - (ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.totalPendingDeposits(isCall)), tvl ); return OptionMath.calculateCLevelDecay( OptionMath.CalculateCLevelDecayArgs( timeIntervalsElapsed64x64, oldCLevel64x64, utilization, 0xb333333333333333, // 0.7 0xe666666666666666, // 0.9 0x10000000000000000, // 1.0 0x10000000000000000, // 1.0 0xe666666666666666, // 0.9 0x56fc2a2c515da32ea // 2e ) ); } /** * @notice calculate updated C-Level, accounting for change in liquidity * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change * @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity * @param newLiquidity64x64 64x64 fixed point representation of current liquidity * @param isCallPool whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function applyCLevelLiquidityChangeAdjustment( Layout storage l, int128 oldCLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal view returns (int128 cLevel64x64) { int128 steepness64x64 = isCallPool ? l.steepnessUnderlying64x64 : l.steepnessBase64x64; // fallback to deprecated storage value if side-specific value is not set if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64; cLevel64x64 = OptionMath.calculateCLevel( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, steepness64x64 ); if (cLevel64x64 < 0xb333333333333333) { cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7 } } /** * @notice set C-Level to arbitrary pre-calculated value * @param cLevel64x64 new C-Level of pool * @param isCallPool whether to update C-Level for call or put pool */ function setCLevel( Layout storage l, int128 cLevel64x64, bool isCallPool ) internal { if (isCallPool) { l.cLevelUnderlying64x64 = cLevel64x64; l.cLevelUnderlyingUpdatedAt = block.timestamp; } else { l.cLevelBase64x64 = cLevel64x64; l.cLevelBaseUpdatedAt = block.timestamp; } } function setOracles( Layout storage l, address baseOracle, address underlyingOracle ) internal { require( AggregatorV3Interface(baseOracle).decimals() == AggregatorV3Interface(underlyingOracle).decimals(), "Pool: oracle decimals must match" ); l.baseOracle = baseOracle; l.underlyingOracle = underlyingOracle; } function fetchPriceUpdate(Layout storage l) internal view returns (int128 price64x64) { int256 priceUnderlying = AggregatorInterface(l.underlyingOracle) .latestAnswer(); int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer(); return ABDKMath64x64.divi(priceUnderlying, priceBase); } /** * @notice set price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to update * @param price64x64 64x64 fixed point representation of price */ function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64 ) internal { uint256 bucket = timestamp / (1 hours); l.bucketPrices64x64[bucket] = price64x64; l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255)); } /** * @notice get price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdate(Layout storage l, uint256 timestamp) internal view returns (int128) { return l.bucketPrices64x64[timestamp / (1 hours)]; } /** * @notice get first price update available following given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdateAfter(Layout storage l, uint256 timestamp) internal view returns (int128) { // price updates are grouped into hourly buckets uint256 bucket = timestamp / (1 hours); // divide by 256 to get the index of the relevant price update sequence uint256 sequenceId = bucket >> 8; // get position within sequence relevant to current price update uint256 offset = bucket & 255; // shift to skip buckets from earlier in sequence uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >> offset; // iterate through future sequences until a price update is found // sequence corresponding to current timestamp used as upper bound uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; } // if no price update is found (sequence == 0) function will return 0 // this should never occur, as each relevant external function triggers a price update // the most significant bit of the sequence corresponds to the offset of the relevant bucket uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; } } return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1]; } function totalPendingDeposits(Layout storage l, bool isCallPool) internal view returns (uint256) { return l.nextDeposits[isCallPool].totalPendingDeposits; } function pendingDepositsOf( Layout storage l, address account, bool isCallPool ) internal view returns (uint256) { return l.pendingDeposits[account][l.nextDeposits[isCallPool].eta][ isCallPool ]; } function contractSizeToBaseTokenAmount( Layout storage l, uint256 contractSize, int128 price64x64, bool isCallPool ) internal view returns (uint256 tokenAmount) { if (isCallPool) { tokenAmount = contractSize; } else { uint256 value = price64x64.mulu(contractSize); int128 value64x64 = ABDKMath64x64Token.fromDecimals( value, l.underlyingDecimals ); tokenAmount = ABDKMath64x64Token.toDecimals( value64x64, l.baseDecimals ); } } function setBuybackEnabled( Layout storage l, bool state, bool isCallPool ) internal { l.isBuybackEnabled[msg.sender][isCallPool] = state; } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {IERC173} from "@solidstate/contracts/access/IERC173.sol"; import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; import {IFeeDiscount} from "../staking/IFeeDiscount.sol"; import {IPoolEvents} from "./IPoolEvents.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; struct Interval { uint256 contractSize; uint256 tokenAmount; uint256 payment; uint256 apyFee; } address internal immutable WETH_ADDRESS; address internal immutable PREMIA_MINING_ADDRESS; address internal immutable FEE_RECEIVER_ADDRESS; address internal immutable FEE_DISCOUNT_ADDRESS; address internal immutable IVOL_ORACLE_ADDRESS; int128 internal immutable FEE_PREMIUM_64x64; int128 internal immutable FEE_APY_64x64; uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID; uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID; uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID; uint256 internal constant INVERSE_BASIS_POINT = 1e4; uint256 internal constant BATCHING_PERIOD = 260; // Minimum APY for capital locked up to underwrite options. // The quote will return a minimum price corresponding to this APY int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3 // Multiply sell quote by this constant int128 internal constant SELL_COEFFICIENT_64x64 = 0xb333333333333333; // 0.7 constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 feePremium64x64, int128 feeApy64x64 ) { IVOL_ORACLE_ADDRESS = ivolOracle; WETH_ADDRESS = weth; PREMIA_MINING_ADDRESS = premiaMining; FEE_RECEIVER_ADDRESS = feeReceiver; // PremiaFeeDiscount contract address FEE_DISCOUNT_ADDRESS = feeDiscountAddress; FEE_PREMIUM_64x64 = feePremium64x64; FEE_APY_64x64 = feeApy64x64; UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_FREE_LIQ, 0, 0 ); BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_FREE_LIQ, 0, 0 ); UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ, 0, 0 ); BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_RESERVED_LIQ, 0, 0 ); } modifier onlyProtocolOwner() { require( msg.sender == IERC173(OwnableStorage.layout().owner).owner(), "Not protocol owner" ); _; } function _fetchFeeDiscount64x64(address feePayer) internal view returns (int128 discount64x64) { if (FEE_DISCOUNT_ADDRESS != address(0)) { discount64x64 = ABDKMath64x64.divu( IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer), INVERSE_BASIS_POINT ); } } function _withdrawFees(bool isCall) internal returns (uint256 amount) { uint256 tokenId = _getReservedLiquidityTokenId(isCall); amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId); if (amount > 0) { _burn(FEE_RECEIVER_ADDRESS, tokenId, amount); _pushTo( FEE_RECEIVER_ADDRESS, PoolStorage.layout().getPoolToken(isCall), amount ); emit FeeWithdrawal(isCall, amount); } } /** * @notice calculate price of option contract * @param args structured quote arguments * @return result quote result */ function _quotePurchasePrice(PoolStorage.QuoteArgsInternal memory args) internal view returns (PoolStorage.QuoteResultInternal memory result) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); (int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l .getRealPoolState(args.isCall); require(oldLiquidity64x64 > 0, "no liq"); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64 ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 collateral64x64 = args.isCall ? contractSize64x64 : contractSize64x64.mul(args.strike64x64); ( int128 price64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) = OptionMath.quotePrice( OptionMath.QuoteArgs( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, adjustedCLevel64x64, oldLiquidity64x64, oldLiquidity64x64.sub(collateral64x64), 0x10000000000000000, // 64x64 fixed point representation of 1 MIN_APY_64x64, args.isCall ) ); result.baseCost64x64 = args.isCall ? price64x64.mul(contractSize64x64).div(args.spot64x64) : price64x64.mul(contractSize64x64); result.feeCost64x64 = result.baseCost64x64.mul(FEE_PREMIUM_64x64); result.cLevel64x64 = cLevel64x64; result.slippageCoefficient64x64 = slippageCoefficient64x64; result.feeCost64x64 -= result.feeCost64x64.mul( _fetchFeeDiscount64x64(args.feePayer) ); } function _quoteSalePrice(PoolStorage.QuoteArgsInternal memory args) internal view returns (int128 baseCost64x64, int128 feeCost64x64) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64 ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 blackScholesPrice64x64 = OptionMath._blackScholesPrice( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, args.isCall ); int128 exerciseValue64x64 = ABDKMath64x64Token.fromDecimals( _calculateExerciseValue( l, args.contractSize, args.spot64x64, args.strike64x64, args.isCall ), l.baseDecimals ); int128 sellCLevel64x64; { uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(args.isCall, true), args.maturity, args.strike64x64 ); // Initialize to avg value, and replace by current if avg not set or current is lower sellCLevel64x64 = l.avgCLevel64x64[longTokenId]; { (int128 currentCLevel64x64, ) = l.getRealPoolState(args.isCall); if ( sellCLevel64x64 == 0 || currentCLevel64x64 < sellCLevel64x64 ) { sellCLevel64x64 = currentCLevel64x64; } } } int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); baseCost64x64 = SELL_COEFFICIENT_64x64 .mul(sellCLevel64x64) .mul( blackScholesPrice64x64.mul(contractSize64x64).sub( exerciseValue64x64 ) ) .add(exerciseValue64x64); if (args.isCall) { baseCost64x64 = baseCost64x64.div(args.spot64x64); } feeCost64x64 = baseCost64x64.mul(FEE_PREMIUM_64x64); feeCost64x64 -= feeCost64x64.mul(_fetchFeeDiscount64x64(args.feePayer)); baseCost64x64 -= feeCost64x64; } function _getAvailableBuybackLiquidity(uint256 shortTokenId) internal view returns (uint256 totalLiquidity) { PoolStorage.Layout storage l = PoolStorage.layout(); EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; (PoolStorage.TokenType tokenType, , ) = PoolStorage.parseTokenId( shortTokenId ); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 length = accounts.length(); for (uint256 i = 0; i < length; i++) { address lp = accounts.at(i); if (l.isBuybackEnabled[lp][isCall]) { totalLiquidity += _balanceOf(lp, shortTokenId); } } } /** * @notice burn corresponding long and short option tokens * @param l storage layout struct * @param account holder of tokens to annihilate * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to annihilate * @return collateralFreed amount of collateral freed, including APY fee rebate */ function _annihilate( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize ) internal returns (uint256 collateralFreed) { uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate unconsumed APY fee so that it may be refunded uint256 intervalApyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); _burn(account, longTokenId, contractSize); uint256 rebate = _fulfillApyFee( l, account, shortTokenId, contractSize, intervalApyFee, isCall ); _burn(account, shortTokenId, contractSize); collateralFreed = tokenAmount + rebate + intervalApyFee; emit Annihilate(shortTokenId, contractSize); } /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param creditMessageValue whether to apply message value as credit towards transfer */ function _deposit( uint256 amount, bool isCallPool, bool creditMessageValue ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); // Reset gradual divestment timestamp delete l.divestmentTimestamps[msg.sender][isCallPool]; _processPendingDeposits(l, isCallPool); l.depositedAt[msg.sender][isCallPool] = block.timestamp; _addUserTVL(l, msg.sender, isCallPool, amount); _pullFrom(l, msg.sender, amount, isCallPool, creditMessageValue); _addToDepositQueue(msg.sender, amount, isCallPool); emit Deposit(msg.sender, isCallPool, amount); } /** * @notice purchase option * @param l storage layout struct * @param account recipient of purchased option * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize size of option contract * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to purchase long position * @return feeCost quantity of tokens required to pay fees */ function _purchase( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns (uint256 baseCost, uint256 feeCost) { require(maturity > block.timestamp, "expired"); require(contractSize >= l.underlyingMinimum, "too small"); { uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); uint256 freeLiquidityTokenId = _getFreeLiquidityTokenId(isCall); require( tokenAmount <= _totalSupply(freeLiquidityTokenId) - l.totalPendingDeposits(isCall) - (_balanceOf(account, freeLiquidityTokenId) - l.pendingDepositsOf(account, isCall)), "insuf liq" ); } PoolStorage.QuoteResultInternal memory quote = _quotePurchasePrice( PoolStorage.QuoteArgsInternal( account, maturity, strike64x64, newPrice64x64, contractSize, isCall ) ); baseCost = ABDKMath64x64Token.toDecimals( quote.baseCost64x64, l.getTokenDecimals(isCall) ); feeCost = ABDKMath64x64Token.toDecimals( quote.feeCost64x64, l.getTokenDecimals(isCall) ); uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, true), maturity, strike64x64 ); _updateCLevelAverage(l, longTokenId, contractSize, quote.cLevel64x64); // mint long option token for buyer _mint(account, longTokenId, contractSize); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); // burn free liquidity tokens from other underwriters _mintShortTokenLoop( l, account, maturity, strike64x64, contractSize, baseCost, isCall ); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall); // mint reserved liquidity tokens for fee receiver _processAvailableFunds( FEE_RECEIVER_ADDRESS, feeCost, isCall, true, false ); emit Purchase( account, longTokenId, contractSize, baseCost, feeCost, newPrice64x64 ); } /** * @notice reassign short position to new underwriter * @param l storage layout struct * @param account holder of positions to be reassigned * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to reassign * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return netCollateralFreed quantity of liquidity freed */ function _reassign( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns ( uint256 baseCost, uint256 feeCost, uint256 netCollateralFreed ) { (baseCost, feeCost) = _purchase( l, account, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); uint256 totalCollateralFreed = _annihilate( l, account, maturity, strike64x64, isCall, contractSize ); netCollateralFreed = totalCollateralFreed - baseCost - feeCost; } /** * @notice exercise option on behalf of holder * @dev used for processing of expired options if passed holder is zero address * @param holder owner of long option tokens to exercise * @param longTokenId long option token id * @param contractSize quantity of tokens to exercise */ function _exercise( address holder, uint256 longTokenId, uint256 contractSize ) internal { uint64 maturity; int128 strike64x64; bool isCall; bool onlyExpired = holder == address(0); { PoolStorage.TokenType tokenType; (tokenType, maturity, strike64x64) = PoolStorage.parseTokenId( longTokenId ); require( tokenType == PoolStorage.TokenType.LONG_CALL || tokenType == PoolStorage.TokenType.LONG_PUT, "invalid type" ); require(!onlyExpired || maturity < block.timestamp, "not expired"); isCall = tokenType == PoolStorage.TokenType.LONG_CALL; } PoolStorage.Layout storage l = PoolStorage.layout(); int128 spot64x64 = _update(l); if (maturity < block.timestamp) { spot64x64 = l.getPriceUpdateAfter(maturity); } require( onlyExpired || ( isCall ? (spot64x64 > strike64x64) : (spot64x64 < strike64x64) ), "not ITM" ); uint256 exerciseValue = _calculateExerciseValue( l, contractSize, spot64x64, strike64x64, isCall ); if (onlyExpired) { // burn long option tokens from multiple holders // transfer profit to and emit Exercise event for each holder in loop _burnLongTokenLoop( contractSize, exerciseValue, longTokenId, isCall ); } else { // burn long option tokens from sender _burnLongTokenInterval( holder, longTokenId, contractSize, exerciseValue, isCall ); } // burn short option tokens from multiple underwriters _burnShortTokenLoop( l, maturity, strike64x64, contractSize, exerciseValue, isCall, false ); } function _calculateExerciseValue( PoolStorage.Layout storage l, uint256 contractSize, int128 spot64x64, int128 strike64x64, bool isCall ) internal view returns (uint256 exerciseValue) { // calculate exercise value if option is in-the-money if (isCall) { if (spot64x64 > strike64x64) { exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu( contractSize ); } } else { if (spot64x64 < strike64x64) { exerciseValue = l.contractSizeToBaseTokenAmount( contractSize, strike64x64.sub(spot64x64), false ); } } } function _mintShortTokenLoop( PoolStorage.Layout storage l, address buyer, uint64 maturity, int128 strike64x64, uint256 contractSize, uint256 premium, bool isCall ) internal { uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate anticipated APY fee so that it may be reserved uint256 apyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); while (tokenAmount > 0) { address underwriter = l.liquidityQueueAscending[isCall][address(0)]; uint256 balance = _balanceOf( underwriter, _getFreeLiquidityTokenId(isCall) ); // if underwriter is in process of divestment, remove from queue if (!l.getReinvestmentStatus(underwriter, isCall)) { _burn(underwriter, _getFreeLiquidityTokenId(isCall), balance); _processAvailableFunds( underwriter, balance, isCall, true, false ); _subUserTVL(l, underwriter, isCall, balance); continue; } // if underwriter has insufficient liquidity, remove from queue if (balance < l.getMinimumAmount(isCall)) { l.removeUnderwriter(underwriter, isCall); continue; } // move interval to end of queue if underwriter is buyer if (underwriter == buyer) { l.removeUnderwriter(underwriter, isCall); l.addUnderwriter(underwriter, isCall); continue; } balance -= l.pendingDepositsOf(underwriter, isCall); Interval memory interval; // amount of liquidity provided by underwriter, accounting for reinvested premium interval.tokenAmount = (balance * (tokenAmount + premium - apyFee)) / tokenAmount; // skip underwriters whose liquidity is pending deposit processing if (interval.tokenAmount == 0) continue; // truncate interval if underwriter has excess liquidity available if (interval.tokenAmount > tokenAmount) interval.tokenAmount = tokenAmount; // calculate derived interval variables interval.contractSize = (contractSize * interval.tokenAmount) / tokenAmount; interval.payment = (premium * interval.tokenAmount) / tokenAmount; interval.apyFee = (apyFee * interval.tokenAmount) / tokenAmount; _mintShortTokenInterval( l, underwriter, buyer, shortTokenId, interval, isCall ); tokenAmount -= interval.tokenAmount; contractSize -= interval.contractSize; premium -= interval.payment; apyFee -= interval.apyFee; } } function _mintShortTokenInterval( PoolStorage.Layout storage l, address underwriter, address longReceiver, uint256 shortTokenId, Interval memory interval, bool isCallPool ) internal { // track prepaid APY fees _reserveApyFee(l, underwriter, shortTokenId, interval.apyFee); // if payment is equal to collateral amount plus APY fee, this is a manual underwrite bool isManualUnderwrite = interval.payment == interval.tokenAmount + interval.apyFee; if (!isManualUnderwrite) { // burn free liquidity tokens from underwriter _burn( underwriter, _getFreeLiquidityTokenId(isCallPool), interval.tokenAmount + interval.apyFee - interval.payment ); } // mint short option tokens for underwriter _mint(underwriter, shortTokenId, interval.contractSize); _addUserTVL( l, underwriter, isCallPool, interval.payment - interval.apyFee ); emit Underwrite( underwriter, longReceiver, shortTokenId, interval.contractSize, isManualUnderwrite ? 0 : interval.payment, isManualUnderwrite ); } function _burnLongTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 longTokenId, bool isCallPool ) internal { EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage .layout() .accountsByToken[longTokenId]; while (contractSize > 0) { address longTokenHolder = holders.at(holders.length() - 1); uint256 intervalContractSize = _balanceOf( longTokenHolder, longTokenId ); // truncate interval if holder has excess long position size if (intervalContractSize > contractSize) intervalContractSize = contractSize; uint256 intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; _burnLongTokenInterval( longTokenHolder, longTokenId, intervalContractSize, intervalExerciseValue, isCallPool ); contractSize -= intervalContractSize; exerciseValue -= intervalExerciseValue; } } function _burnLongTokenInterval( address holder, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, bool isCallPool ) internal { _burn(holder, longTokenId, contractSize); if (exerciseValue > 0) { _processAvailableFunds( holder, exerciseValue, isCallPool, true, true ); } emit Exercise(holder, longTokenId, contractSize, exerciseValue, 0); } function _burnShortTokenLoop( PoolStorage.Layout storage l, uint64 maturity, int128 strike64x64, uint256 contractSize, uint256 payment, bool isCall, bool onlyBuybackLiquidity ) internal { uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate unconsumed APY fee so that it may be refunded uint256 apyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; uint256 index = underwriters.length(); while (contractSize > 0) { address underwriter = underwriters.at(--index); // skip underwriters who do not provide buyback liqudity, if applicable if ( onlyBuybackLiquidity && !l.isBuybackEnabled[underwriter][isCall] ) continue; Interval memory interval; // amount of liquidity provided by underwriter interval.contractSize = _balanceOf(underwriter, shortTokenId); // truncate interval if underwriter has excess short position size if (interval.contractSize > contractSize) interval.contractSize = contractSize; // calculate derived interval variables interval.tokenAmount = (tokenAmount * interval.contractSize) / contractSize; interval.payment = (payment * interval.contractSize) / contractSize; interval.apyFee = (apyFee * interval.contractSize) / contractSize; _burnShortTokenInterval( l, underwriter, shortTokenId, interval, isCall, onlyBuybackLiquidity ); contractSize -= interval.contractSize; tokenAmount -= interval.tokenAmount; payment -= interval.payment; apyFee -= interval.apyFee; } } function _burnShortTokenInterval( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, Interval memory interval, bool isCallPool, bool isSale ) internal { // track prepaid APY fees uint256 refundWithRebate = interval.apyFee + _fulfillApyFee( l, underwriter, shortTokenId, interval.contractSize, interval.apyFee, isCallPool ); // burn short option tokens from underwriter _burn(underwriter, shortTokenId, interval.contractSize); bool divest = !l.getReinvestmentStatus(underwriter, isCallPool); _processAvailableFunds( underwriter, interval.tokenAmount - interval.payment + refundWithRebate, isCallPool, divest, false ); if (divest) { _subUserTVL(l, underwriter, isCallPool, interval.tokenAmount); } else { if (refundWithRebate > interval.payment) { _addUserTVL( l, underwriter, isCallPool, refundWithRebate - interval.payment ); } else if (interval.payment > refundWithRebate) { _subUserTVL( l, underwriter, isCallPool, interval.payment - refundWithRebate ); } } if (isSale) { emit AssignSale( underwriter, shortTokenId, interval.tokenAmount - interval.payment, interval.contractSize ); } else { emit AssignExercise( underwriter, shortTokenId, interval.tokenAmount - interval.payment, interval.contractSize, 0 ); } } function _calculateApyFee( PoolStorage.Layout storage l, uint256 shortTokenId, uint256 tokenAmount, uint64 maturity ) internal view returns (uint256 apyFee) { if (block.timestamp < maturity) { int128 apyFeeRate64x64 = _totalSupply(shortTokenId) == 0 ? FEE_APY_64x64 : l.feeReserveRates[shortTokenId]; apyFee = apyFeeRate64x64.mulu( (tokenAmount * (maturity - block.timestamp)) / (365 days) ); } } function _reserveApyFee( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, uint256 amount ) internal { l.feesReserved[underwriter][shortTokenId] += amount; emit APYFeeReserved(underwriter, shortTokenId, amount); } /** * @notice credit fee receiver with fees earned and calculate rebate for underwriter * @dev short tokens which have acrrued fee must not be burned or transferred until after this helper is called * @param l storage layout struct * @param underwriter holder of short position who reserved fees * @param shortTokenId short token id whose reserved fees to pay and rebate * @param intervalContractSize size of position for which to calculate accrued fees * @param intervalApyFee quantity of fees reserved but not yet accrued * @param isCallPool true for call, false for put */ function _fulfillApyFee( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalApyFee, bool isCallPool ) internal returns (uint256 rebate) { if (intervalApyFee == 0) return 0; // calculate proportion of fees reserved corresponding to interval uint256 feesReserved = l.feesReserved[underwriter][shortTokenId]; uint256 intervalFeesReserved = (feesReserved * intervalContractSize) / _balanceOf(underwriter, shortTokenId); // deduct fees for time not elapsed l.feesReserved[underwriter][shortTokenId] -= intervalFeesReserved; // apply rebate to fees accrued rebate = _fetchFeeDiscount64x64(underwriter).mulu( intervalFeesReserved - intervalApyFee ); // credit fee receiver with fees paid uint256 intervalFeesPaid = intervalFeesReserved - intervalApyFee - rebate; _processAvailableFunds( FEE_RECEIVER_ADDRESS, intervalFeesPaid, isCallPool, true, false ); emit APYFeePaid(underwriter, shortTokenId, intervalFeesPaid); } function _addToDepositQueue( address account, uint256 amount, bool isCallPool ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); _mint(account, _getFreeLiquidityTokenId(isCallPool), amount); uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) * BATCHING_PERIOD + BATCHING_PERIOD; l.pendingDeposits[account][nextBatch][isCallPool] += amount; PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool]; batchData.totalPendingDeposits += amount; batchData.eta = nextBatch; } function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall) internal { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; if (batchData.eta == 0 || block.timestamp < batchData.eta) return; int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel( l, oldLiquidity64x64, oldLiquidity64x64.add( ABDKMath64x64Token.fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) ), isCall ); delete l.nextDeposits[isCall]; } function _getFreeLiquidityTokenId(bool isCall) internal view returns (uint256 freeLiqTokenId) { freeLiqTokenId = isCall ? UNDERLYING_FREE_LIQ_TOKEN_ID : BASE_FREE_LIQ_TOKEN_ID; } function _getReservedLiquidityTokenId(bool isCall) internal view returns (uint256 reservedLiqTokenId) { reservedLiqTokenId = isCall ? UNDERLYING_RESERVED_LIQ_TOKEN_ID : BASE_RESERVED_LIQ_TOKEN_ID; } function _setCLevel( PoolStorage.Layout storage l, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal { int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool); int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, isCallPool ); l.setCLevel(cLevel64x64, isCallPool); emit UpdateCLevel( isCallPool, cLevel64x64, oldLiquidity64x64, newLiquidity64x64 ); } function _updateCLevelAverage( PoolStorage.Layout storage l, uint256 longTokenId, uint256 contractSize, int128 cLevel64x64 ) internal { int128 supply64x64 = ABDKMath64x64Token.fromDecimals( _totalSupply(longTokenId), l.underlyingDecimals ); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( contractSize, l.underlyingDecimals ); l.avgCLevel64x64[longTokenId] = l .avgCLevel64x64[longTokenId] .mul(supply64x64) .add(cLevel64x64.mul(contractSize64x64)) .div(supply64x64.add(contractSize64x64)); } /** * @notice calculate and store updated market state * @param l storage layout struct * @return newPrice64x64 64x64 fixed point representation of current spot price */ function _update(PoolStorage.Layout storage l) internal returns (int128 newPrice64x64) { if (l.updatedAt == block.timestamp) { return (l.getPriceUpdate(block.timestamp)); } newPrice64x64 = l.fetchPriceUpdate(); if (l.getPriceUpdate(block.timestamp) == 0) { l.setPriceUpdate(block.timestamp, newPrice64x64); } l.updatedAt = block.timestamp; _processPendingDeposits(l, true); _processPendingDeposits(l, false); } /** * @notice transfer ERC20 tokens to message sender * @param token ERC20 token address * @param amount quantity of token to transfer */ function _pushTo( address to, address token, uint256 amount ) internal { if (amount == 0) return; require(IERC20(token).transfer(to, amount), "ERC20 transfer failed"); } /** * @notice transfer ERC20 tokens from message sender * @param l storage layout struct * @param from address from which tokens are pulled from * @param amount quantity of token to transfer * @param isCallPool whether funds correspond to call or put pool * @param creditMessageValue whether to attempt to treat message value as credit */ function _pullFrom( PoolStorage.Layout storage l, address from, uint256 amount, bool isCallPool, bool creditMessageValue ) internal { uint256 credit; if (creditMessageValue) { credit = _creditMessageValue(amount, isCallPool); } if (amount > credit) { credit += _creditReservedLiquidity( from, amount - credit, isCallPool ); } if (amount > credit) { require( IERC20(l.getPoolToken(isCallPool)).transferFrom( from, address(this), amount - credit ), "ERC20 transfer failed" ); } } /** * @notice transfer or reinvest available user funds * @param account owner of funds * @param amount quantity of funds available * @param isCallPool whether funds correspond to call or put pool * @param divest whether to reserve funds or reinvest * @param transferOnDivest whether to transfer divested funds to owner */ function _processAvailableFunds( address account, uint256 amount, bool isCallPool, bool divest, bool transferOnDivest ) internal { if (divest) { if (transferOnDivest) { _pushTo( account, PoolStorage.layout().getPoolToken(isCallPool), amount ); } else { _mint( account, _getReservedLiquidityTokenId(isCallPool), amount ); } } else { _addToDepositQueue(account, amount, isCallPool); } } /** * @notice validate that pool accepts ether deposits and calculate credit amount from message value * @param amount total deposit quantity * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @return credit quantity of credit to apply */ function _creditMessageValue(uint256 amount, bool isCallPool) internal returns (uint256 credit) { if (msg.value > 0) { require( PoolStorage.layout().getPoolToken(isCallPool) == WETH_ADDRESS, "not WETH deposit" ); if (msg.value > amount) { unchecked { (bool success, ) = payable(msg.sender).call{ value: msg.value - amount }(""); require(success, "ETH refund failed"); credit = amount; } } else { credit = msg.value; } IWETH(WETH_ADDRESS).deposit{value: credit}(); } } /** * @notice calculate credit amount from reserved liquidity * @param account address whose reserved liquidity to use as credit * @param amount total deposit quantity * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @return credit quantity of credit to apply */ function _creditReservedLiquidity( address account, uint256 amount, bool isCallPool ) internal returns (uint256 credit) { uint256 reservedLiqTokenId = _getReservedLiquidityTokenId(isCallPool); uint256 balance = _balanceOf(account, reservedLiqTokenId); if (balance > 0) { credit = balance > amount ? amount : balance; _burn(account, reservedLiqTokenId, credit); } } function _mint( address account, uint256 tokenId, uint256 amount ) internal { _mint(account, tokenId, amount, ""); } function _addUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL + amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL + amount; l.totalTVL[isCallPool] = totalTVL + amount; } function _subUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; uint256 newUserTVL; uint256 newTotalTVL; if (userTVL > amount) { newUserTVL = userTVL - amount; } if (totalTVL > amount) { newTotalTVL = totalTVL - amount; } IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, newUserTVL, totalTVL ); l.userTVL[user][isCallPool] = newUserTVL; l.totalTVL[isCallPool] = newTotalTVL; } /** * @notice ERC1155 hook: track eligible underwriters * @param operator transaction sender * @param from token sender * @param to token receiver * @param ids token ids transferred * @param amounts token quantities transferred * @param data data payload */ 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); PoolStorage.Layout storage l = PoolStorage.layout(); for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; if (amount == 0) continue; if (from == address(0)) { l.tokenIds.add(id); } if (to == address(0) && _totalSupply(id) == 0) { l.tokenIds.remove(id); } // prevent transfer of free and reserved liquidity during waiting period if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID || id == BASE_RESERVED_LIQ_TOKEN_ID ) { if (from != address(0) && to != address(0)) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID; require( l.depositedAt[from][isCallPool] + (1 days) < block.timestamp, "liq lock 1d" ); } } if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID ) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 minimum = l.getMinimumAmount(isCallPool); if (from != address(0)) { uint256 balance = _balanceOf(from, id); if (balance > minimum && balance <= amount + minimum) { require( balance - l.pendingDepositsOf(from, isCallPool) >= amount, "Insuf balance" ); l.removeUnderwriter(from, isCallPool); } if (to != address(0)) { _subUserTVL(l, from, isCallPool, amount); _addUserTVL(l, to, isCallPool, amount); } } if (to != address(0)) { uint256 balance = _balanceOf(to, id); if (balance <= minimum && balance + amount >= minimum) { l.addUnderwriter(to, isCallPool); } } } // Update userTVL on SHORT options transfers (PoolStorage.TokenType tokenType, , ) = PoolStorage.parseTokenId( id ); if ( tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.SHORT_PUT ) { _beforeShortTokenTransfer(l, from, to, id, amount); } } } function _beforeShortTokenTransfer( PoolStorage.Layout storage l, address from, address to, uint256 id, uint256 amount ) private { // total supply has already been updated, so compare to amount rather than 0 if (from == address(0) && _totalSupply(id) == amount) { l.feeReserveRates[id] = FEE_APY_64x64; } if (to == address(0) && _totalSupply(id) == 0) { delete l.feeReserveRates[id]; } if (from != address(0) && to != address(0)) { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(id); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 collateral = l.contractSizeToBaseTokenAmount( amount, strike64x64, isCall ); uint256 intervalApyFee = _calculateApyFee( l, id, collateral, maturity ); uint256 rebate = _fulfillApyFee( l, from, id, amount, intervalApyFee, isCall ); _reserveApyFee(l, to, id, intervalApyFee); bool divest = !l.getReinvestmentStatus(from, isCall); if (rebate > 0) { _processAvailableFunds(from, rebate, isCall, divest, false); } _subUserTVL( l, from, isCall, divest ? collateral : collateral - rebate ); _addUserTVL(l, to, isCall, collateral); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC165Storage { struct Layout { mapping(bytes4 => bool) supportedInterfaces; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC165'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function isSupportedInterface(Layout storage l, bytes4 interfaceId) internal view returns (bool) { return l.supportedInterfaces[interfaceId]; } function setSupportedInterface( Layout storage l, bytes4 interfaceId, bool status ) internal { require(interfaceId != 0xffffffff, 'ERC165: invalid interface id'); l.supportedInterfaces[interfaceId] = status; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Set implementation with enumeration functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license) */ library EnumerableSet { struct Set { bytes32[] _values; // 1-indexed to allow 0 to signify nonexistence mapping(bytes32 => uint256) _indexes; } struct Bytes32Set { Set _inner; } struct AddressSet { Set _inner; } struct UintSet { Set _inner; } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) { return _indexOf(set._inner, value); } function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(uint256(uint160(value)))); } function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(value)); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } 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]; } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _indexOf(Set storage set, bytes32 value) private view returns (uint256) { unchecked { return set._indexes[value] - 1; } } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { unchecked { bytes32 last = set._values[set._values.length - 1]; // move last value to now-vacant index set._values[valueIndex - 1] = last; set._indexes[last] = valueIndex; } // clear last index set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155 } from '../IERC1155.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal { /** * @inheritdoc IERC1155 */ function balanceOf(address account, uint256 id) public view virtual returns (uint256) { return _balanceOf(account, id); } /** * @inheritdoc IERC1155 */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual returns (uint256[] memory) { require( accounts.length == ids.length, 'ERC1155: accounts and ids length mismatch' ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; uint256[] memory batchBalances = new uint256[](accounts.length); unchecked { for (uint256 i; i < accounts.length; i++) { require( accounts[i] != address(0), 'ERC1155: batch balance query for the zero address' ); batchBalances[i] = balances[ids[i]][accounts[i]]; } } return batchBalances; } /** * @inheritdoc IERC1155 */ function isApprovedForAll(address account, address operator) public view virtual returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @inheritdoc IERC1155 */ function setApprovalForAll(address operator, bool status) public virtual { require( msg.sender != operator, 'ERC1155: setting approval status for self' ); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][ operator ] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @inheritdoc IERC1155 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @inheritdoc IERC1155 */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155 enumerable and aggregate function interface */ interface IERC1155Enumerable { /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function totalSupply(uint256 id) external view returns (uint256); /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function totalHolders(uint256 id) external view returns (uint256); /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function accountsByToken(uint256 id) external view returns (address[] memory); /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function tokensByAccount(address account) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol'; import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol'; /** * @title ERC1155Enumerable internal functions */ abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function _totalSupply(uint256 id) internal view virtual returns (uint256) { return ERC1155EnumerableStorage.layout().totalSupply[id]; } /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function _totalHolders(uint256 id) internal view virtual returns (uint256) { return ERC1155EnumerableStorage.layout().accountsByToken[id].length(); } /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function _accountsByToken(uint256 id) internal view virtual returns (address[] memory) { EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[id]; address[] memory addresses = new address[](accounts.length()); unchecked { for (uint256 i; i < accounts.length(); i++) { addresses[i] = accounts.at(i); } } return addresses; } /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function _tokensByAccount(address account) internal view virtual returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); unchecked { for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } } return ids; } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155BaseInternal */ 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 != to) { ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage .layout(); mapping(uint256 => EnumerableSet.AddressSet) storage tokenAccounts = l.accountsByToken; EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from]; EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to]; for (uint256 i; i < ids.length; ) { uint256 amount = amounts[i]; if (amount > 0) { uint256 id = ids[i]; if (from == address(0)) { l.totalSupply[id] += amount; } else if (_balanceOf(from, id) == amount) { tokenAccounts[id].remove(from); fromTokens.remove(id); } if (to == address(0)) { l.totalSupply[id] -= amount; } else if (_balanceOf(to, id) == 0) { tokenAccounts[id].add(to); toTokens.add(id); } } unchecked { i++; } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155Internal } from './IERC1155Internal.sol'; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice ERC1155 interface * @dev see https://github.com/ethereum/EIPs/issues/1155 */ interface IERC1155 is IERC1155Internal, IERC165 { /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll(address operator, bool status) external; /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ 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 { IERC165 } from '../../introspection/IERC165.sol'; /** * @title ERC1155 transfer receiver interface */ interface IERC1155Receiver is IERC165 { /** * @notice validate receipt of ERC1155 transfer * @param operator executor of transfer * @param from sender of tokens * @param id token ID received * @param value quantity of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice validate receipt of ERC1155 batch transfer * @param operator executor of transfer * @param from sender of tokens * @param ids token IDs received * @param values quantities of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ 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 { AddressUtils } from '../../../utils/AddressUtils.sol'; import { IERC1155Internal } from '../IERC1155Internal.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol'; /** * @title Base ERC1155 internal functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155BaseInternal is IERC1155Internal { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function _balanceOf(address account, uint256 id) internal view virtual returns (uint256) { require( account != address(0), 'ERC1155: balance query for the zero address' ); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer( msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); ERC1155BaseStorage.layout().balances[id][account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { _mint(account, id, amount, data); _doSafeTransferAcceptanceCheck( msg.sender, address(0), account, id, amount, data ); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer( msg.sender, address(0), account, ids, amounts, data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; ) { balances[ids[i]][account] += amounts[i]; unchecked { i++; } } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _mintBatch(account, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), account, ids, amounts, data ); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer( msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), '' ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; unchecked { require( balances[account] >= amount, 'ERC1155: burn amount exceeds balances' ); balances[account] -= amount; } emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ 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' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); _beforeTokenTransfer( operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { uint256 senderBalance = balances[id][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { _transfer(operator, sender, recipient, id, amount, data); _doSafeTransferAcceptanceCheck( operator, sender, recipient, id, amount, data ); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; ) { uint256 token = ids[i]; uint256 amount = amounts[i]; unchecked { uint256 senderBalance = balances[token][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[token][sender] = senderBalance - amount; i++; } // balance increase cannot be unchecked because ERC1155Base neither tracks nor validates a totalSupply balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _transferBatch(operator, sender, recipient, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, sender, recipient, ids, amounts, data ); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ 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) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ 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) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implementation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice Partial ERC1155 interface needed by internal functions */ interface IERC1155Internal { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { UintUtils } from './UintUtils.sol'; library AddressUtils { using UintUtils for uint256; function toString(address account) internal pure returns (string memory) { return uint256(uint160(account)).toHexString(20); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable account, uint256 amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall( address target, bytes memory data, string memory error ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'AddressUtils: failed low-level call with value' ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) internal returns (bytes memory) { require( address(this).balance >= value, 'AddressUtils: insufficient balance for call' ); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) private returns (bytes memory) { require( isContract(target), 'AddressUtils: function call to non-contract' ); (bool success, bytes memory returnData) = target.call{ value: value }( data ); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC1155BaseStorage { struct Layout { mapping(uint256 => mapping(address => uint256)) balances; mapping(address => mapping(address => bool)) operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Base'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title utility functions for uint256 operations * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ library UintUtils { bytes16 private constant HEX_SYMBOLS = '0123456789abcdef'; function toString(uint256 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); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 length = 0; for (uint256 temp = value; temp != 0; temp >>= 8) { unchecked { length++; } } return toHexString(value, 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'; unchecked { for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_SYMBOLS[value & 0xf]; value >>= 4; } } require(value == 0, 'UintUtils: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; library ERC1155EnumerableStorage { struct Layout { mapping(uint256 => uint256) totalSupply; mapping(uint256 => EnumerableSet.AddressSet) accountsByToken; mapping(address => EnumerableSet.UintSet) tokensByAccount; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Enumerable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Interface for the Multicall utility contract */ interface IMulticall { /** * @notice batch function calls to the contract and return the results of each * @param data array of function call data payloads * @return results array of function call results */ function multicall(bytes[] calldata data) external returns (bytes[] memory results); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library ABDKMath64x64Token { using ABDKMath64x64 for int128; /** * @notice convert 64x64 fixed point representation of token amount to decimal * @param value64x64 64x64 fixed point representation of token amount * @param decimals token display decimals * @return value decimal representation of token amount */ function toDecimals(int128 value64x64, uint8 decimals) internal pure returns (uint256 value) { value = value64x64.mulu(10**decimals); } /** * @notice convert decimal representation of token amount to 64x64 fixed point * @param value decimal representation of token amount * @param decimals token display decimals * @return value64x64 64x64 fixed point representation of token amount */ function fromDecimals(uint256 value, uint8 decimals) internal pure returns (int128 value64x64) { value64x64 = ABDKMath64x64.divu(value, 10**decimals); } /** * @notice convert 64x64 fixed point representation of token amount to wei (18 decimals) * @param value64x64 64x64 fixed point representation of token amount * @return value wei representation of token amount */ function toWei(int128 value64x64) internal pure returns (uint256 value) { value = toDecimals(value64x64, 18); } /** * @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point * @param value wei representation of token amount * @return value64x64 64x64 fixed point representation of token amount */ function fromWei(uint256 value) internal pure returns (int128 value64x64) { value64x64 = fromDecimals(value, 18); } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library OptionMath { using ABDKMath64x64 for int128; struct QuoteArgs { int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years) int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase int128 oldPoolState; // 64x64 fixed point representation of current state of the pool int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options bool isCall; // whether to price "call" or "put" option } struct CalculateCLevelDecayArgs { int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate int128 utilizationLowerBound64x64; int128 utilizationUpperBound64x64; int128 cLevelLowerBound64x64; int128 cLevelUpperBound64x64; int128 cConvergenceULowerBound64x64; int128 cConvergenceUUpperBound64x64; } // 64x64 fixed point integer constants int128 internal constant ONE_64x64 = 0x10000000000000000; int128 internal constant THREE_64x64 = 0x30000000000000000; // 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989 int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989 int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989 /** * @notice recalculate C-Level based on change in liquidity * @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update * @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update * @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update * @param steepness64x64 64x64 fixed point representation of steepness coefficient * @return 64x64 fixed point representation of new C-Level */ function calculateCLevel( int128 initialCLevel64x64, int128 oldPoolState64x64, int128 newPoolState64x64, int128 steepness64x64 ) external pure returns (int128) { return newPoolState64x64 .sub(oldPoolState64x64) .div( oldPoolState64x64 > newPoolState64x64 ? oldPoolState64x64 : newPoolState64x64 ) .mul(steepness64x64) .neg() .exp() .mul(initialCLevel64x64); } /** * @notice calculate the price of an option using the Premia Finance model * @param args arguments of quotePrice * @return premiaPrice64x64 64x64 fixed point representation of Premia option price * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase */ function quotePrice(QuoteArgs memory args) external pure returns ( int128 premiaPrice64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) { int128 deltaPoolState64x64 = args .newPoolState .sub(args.oldPoolState) .div(args.oldPoolState) .mul(args.steepness64x64); int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp(); int128 blackScholesPrice64x64 = _blackScholesPrice( args.varianceAnnualized64x64, args.strike64x64, args.spot64x64, args.timeToMaturity64x64, args.isCall ); cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64); slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div( deltaPoolState64x64 ); premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul( slippageCoefficient64x64 ); int128 intrinsicValue64x64; if (args.isCall && args.strike64x64 < args.spot64x64) { intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64); } else if (!args.isCall && args.strike64x64 > args.spot64x64) { intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64); } int128 collateralValue64x64 = args.isCall ? args.spot64x64 : args.strike64x64; int128 minPrice64x64 = intrinsicValue64x64.add( collateralValue64x64.mul(args.minAPY64x64).mul( args.timeToMaturity64x64 ) ); if (minPrice64x64 > premiaPrice64x64) { premiaPrice64x64 = minPrice64x64; } } /** * @notice calculate the decay of C-Level based on heat diffusion function * @param args structured CalculateCLevelDecayArgs * @return cLevelDecayed64x64 C-Level after accounting for decay */ function calculateCLevelDecay(CalculateCLevelDecayArgs memory args) external pure returns (int128 cLevelDecayed64x64) { int128 convFHighU64x64 = (args.utilization64x64 >= args.utilizationUpperBound64x64 && args.oldCLevel64x64 <= args.cLevelLowerBound64x64) ? ONE_64x64 : int128(0); int128 convFLowU64x64 = (args.utilization64x64 <= args.utilizationLowerBound64x64 && args.oldCLevel64x64 >= args.cLevelUpperBound64x64) ? ONE_64x64 : int128(0); cLevelDecayed64x64 = args .oldCLevel64x64 .sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64)) .sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)) .mul( convFLowU64x64 .mul(ONE_64x64.sub(args.utilization64x64)) .add(convFHighU64x64.mul(args.utilization64x64)) .mul(args.timeIntervalsElapsed64x64) .neg() .exp() ) .add( args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add( args.cConvergenceUUpperBound64x64.mul(convFHighU64x64) ) ); } /** * @notice calculate the exponential decay coefficient for a given interval * @param oldTimestamp timestamp of previous update * @param newTimestamp current timestamp * @return 64x64 fixed point representation of exponential decay coefficient */ function _decay(uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (int128) { return ONE_64x64.sub( (-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp() ); } /** * @notice calculate Choudhury’s approximation of the Black-Scholes CDF * @param input64x64 64x64 fixed point representation of random variable * @return 64x64 fixed point representation of the approximated CDF of x */ function _N(int128 input64x64) internal pure returns (int128) { // squaring via mul is cheaper than via pow int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64; } /** * @notice calculate the price of an option using the Black-Scholes model * @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance * @param strike64x64 64x64 fixed point representation of strike price * @param spot64x64 64x64 fixed point representation of spot price * @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years) * @param isCall whether to price "call" or "put" option * @return 64x64 fixed point representation of Black-Scholes option price */ function _blackScholesPrice( int128 varianceAnnualized64x64, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) internal pure returns (int128) { int128 cumulativeVariance64x64 = timeToMaturity64x64.mul( varianceAnnualized64x64 ); int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt(); int128 d1_64x64 = spot64x64 .div(strike64x64) .ln() .add(cumulativeVariance64x64 >> 1) .div(cumulativeVarianceSqrt64x64); int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64); if (isCall) { return spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64))); } else { return -spot64x64.mul(_N(-d1_64x64)).sub( strike64x64.mul(_N(-d2_64x64)) ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner() external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership(address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.Ownable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner(Layout storage l, address owner) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20Internal } from './IERC20Internal.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 is IERC20Internal { /** * @notice query the total minted token supply * @return token supply */ function totalSupply() external view returns (uint256); /** * @notice query the token balance of given account * @param account address to query * @return token balance */ function balanceOf(address account) external view returns (uint256); /** * @notice query the allowance granted from given holder to given spender * @param holder approver of allowance * @param spender recipient of allowance * @return token allowance */ function allowance(address holder, address spender) external view returns (uint256); /** * @notice grant approval to spender to spend tokens * @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729) * @param spender recipient of allowance * @param amount quantity of tokens approved for spending * @return success status (always true; otherwise function should revert) */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient on behalf of given holder * @param holder holder of tokens prior to transfer * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transferFrom( address holder, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol'; /** * @title WETH (Wrapped ETH) interface */ interface IWETH is IERC20, IERC20Metadata { /** * @notice convert ETH to WETH */ function deposit() external payable; /** * @notice convert WETH to ETH * @dev if caller is a contract, it should have a fallback or receive function * @param amount quantity of WETH to convert, denominated in wei */ function withdraw(uint256 amount) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {FeeDiscountStorage} from "./FeeDiscountStorage.sol"; interface IFeeDiscount { event Staked( address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil ); event Unstaked(address indexed user, uint256 amount); struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } /** * @notice Stake using IERC2612 permit * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) * @param deadline Deadline after which permit will fail * @param v V * @param r R * @param s S */ function stakeWithPermit( uint256 amount, uint256 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Lockup xPremia for protocol fee discounts * Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) */ function stake(uint256 amount, uint256 period) external; /** * @notice Unstake xPremia (If lockup period has ended) * @param amount The amount of xPremia to unstake */ function unstake(uint256 amount) external; ////////// // View // ////////// /** * Calculate the stake amount of a user, after applying the bonus from the lockup period chosen * @param user The user from which to query the stake amount * @return The user stake amount after applying the bonus */ function getStakeAmountWithBonus(address user) external view returns (uint256); /** * @notice Calculate the % of fee discount for user, based on his stake * @param user The _user for which the discount is for * @return Percentage of protocol fee discount (in basis point) * Ex : 1000 = 10% fee discount */ function getDiscount(address user) external view returns (uint256); /** * @notice Get stake levels * @return Stake levels * Ex : 2500 = -25% */ function getStakeLevels() external returns (StakeLevel[] memory); /** * @notice Get stake period multiplier * @param period The duration (in seconds) for which tokens are locked * @return The multiplier for this staking period * Ex : 20000 = x2 */ function getStakePeriodMultiplier(uint256 period) external returns (uint256); /** * @notice Get staking infos of a user * @param user The user address for which to get staking infos * @return The staking infos of the user */ function getUserInfo(address user) external view returns (FeeDiscountStorage.UserInfo memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolEvents { event Purchase( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Sell( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Exercise( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, uint256 fee ); event Underwrite( address indexed underwriter, address indexed longReceiver, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalPremium, bool isManualUnderwrite ); event AssignExercise( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize, uint256 fee ); event AssignSale( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize ); event Deposit(address indexed user, bool isCallPool, uint256 amount); event Withdrawal( address indexed user, bool isCallPool, uint256 depositedAt, uint256 amount ); event FeeWithdrawal(bool indexed isCallPool, uint256 amount); event APYFeeReserved( address underwriter, uint256 shortTokenId, uint256 amount ); event APYFeePaid(address underwriter, uint256 shortTokenId, uint256 amount); event Annihilate(uint256 shortTokenId, uint256 amount); event UpdateCLevel( bool indexed isCall, int128 cLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64 ); event UpdateSteepness(int128 steepness64x64, bool isCallPool); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {PremiaMiningStorage} from "./PremiaMiningStorage.sol"; interface IPremiaMining { function addPremiaRewards(uint256 _amount) external; function premiaRewardsAvailable() external view returns (uint256); function getTotalAllocationPoints() external view returns (uint256); function getPoolInfo(address pool, bool isCallPool) external view returns (PremiaMiningStorage.PoolInfo memory); function getPremiaPerYear() external view returns (uint256); function addPool(address _pool, uint256 _allocPoints) external; function setPoolAllocPoints( address[] memory _pools, uint256[] memory _allocPoints ) external; function pendingPremia( address _pool, bool _isCallPool, address _user ) external view returns (uint256); function updatePool( address _pool, bool _isCallPool, uint256 _totalTVL ) external; function allocatePending( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; function claim( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol"; interface IVolatilitySurfaceOracle { /** * @notice Pack IV model parameters into a single bytes32 * @dev This function is used to pack the parameters into a single variable, which is then used as input in `update` * @param params Parameters of IV model to pack * @return result The packed parameters of IV model */ function formatParams(int256[5] memory params) external pure returns (bytes32 result); /** * @notice Unpack IV model parameters from a bytes32 * @param input Packed IV model parameters to unpack * @return params The unpacked parameters of the IV model */ function parseParams(bytes32 input) external pure returns (int256[] memory params); /** * @notice Get the list of whitelisted relayers * @return The list of whitelisted relayers */ function getWhitelistedRelayers() external view returns (address[] memory); /** * @notice Get the IV model parameters of a token pair * @param base The base token of the pair * @param underlying The underlying token of the pair * @return The IV model parameters */ function getParams(address base, address underlying) external view returns (VolatilitySurfaceOracleStorage.Update memory); /** * @notice Get unpacked IV model parameters * @param base The base token of the pair * @param underlying The underlying token of the pair * @return The unpacked IV model parameters */ function getParamsUnpacked(address base, address underlying) external view returns (int256[] memory); /** * @notice Get time to maturity in years, as a 64x64 fixed point representation * @param maturity Maturity timestamp * @return Time to maturity (in years), as a 64x64 fixed point representation */ function getTimeToMaturity64x64(uint64 maturity) external view returns (int128); /** * @notice calculate the annualized volatility for given set of parameters * @param base The base token of the pair * @param underlying The underlying token of the pair * @param spot64x64 64x64 fixed point representation of spot price * @param strike64x64 64x64 fixed point representation of strike price * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @return 64x64 fixed point representation of annualized implied volatility, where 1 is defined as 100% */ function getAnnualizedVolatility64x64( address base, address underlying, int128 spot64x64, int128 strike64x64, int128 timeToMaturity64x64 ) external view returns (int128); /** * @notice calculate the price of an option using the Black-Scholes model * @param base The base token of the pair * @param underlying The underlying token of the pair * @param strike64x64 Strike, as a64x64 fixed point representation * @param spot64x64 Spot price, as a 64x64 fixed point representation * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @param isCall Whether it is for call or put * @return 64x64 fixed point representation of the Black Scholes price */ function getBlackScholesPrice64x64( address base, address underlying, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); /** * @notice Get Black Scholes price as an uint256 with 18 decimals * @param base The base token of the pair * @param underlying The underlying token of the pair * @param strike64x64 Strike, as a64x64 fixed point representation * @param spot64x64 Spot price, as a 64x64 fixed point representation * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @param isCall Whether it is for call or put * @return Black scholes price, as an uint256 with 18 decimals */ function getBlackScholesPrice( address base, address underlying, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (uint256); /** * @notice Add relayers to the whitelist so that they can add oracle surfaces * @param accounts The addresses to add to the whitelist */ function addWhitelistedRelayers(address[] memory accounts) external; /** * @notice Remove relayers from the whitelist so that they cannot add oracle surfaces * @param accounts The addresses to remove from the whitelist */ function removeWhitelistedRelayers(address[] memory accounts) external; /** * @notice Update a list of IV model parameters * @param base List of base tokens * @param underlying List of underlying tokens * @param parameters List of IV model parameters */ function updateParams( address[] memory base, address[] memory underlying, bytes32[] memory parameters ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Partial ERC20 interface needed by internal functions */ interface IERC20Internal { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library FeeDiscountStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaFeeDiscount"); struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct Layout { // User data with xPREMIA balance staked and date at which lock ends mapping(address => UserInfo) userInfo; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library PremiaMiningStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaMining"); // Info of each pool. struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block. uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below. } // Info of each user. struct UserInfo { uint256 reward; // Total allocated unclaimed reward uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PREMIA // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct Layout { // Total PREMIA left to distribute uint256 premiaAvailable; // Amount of premia distributed per year uint256 premiaPerYear; // pool -> isCallPool -> PoolInfo mapping(address => mapping(bool => PoolInfo)) poolInfo; // pool -> isCallPool -> user -> UserInfo mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; library VolatilitySurfaceOracleStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilitySurfaceOracle"); uint256 internal constant PARAM_BITS = 51; uint256 internal constant PARAM_BITS_MINUS_ONE = 50; uint256 internal constant PARAM_AMOUNT = 5; // START_BIT = PARAM_BITS * (PARAM_AMOUNT - 1) uint256 internal constant START_BIT = 204; struct Update { uint256 updatedAt; bytes32 params; } struct Layout { // Base token -> Underlying token -> Update mapping(address => mapping(address => Update)) parameters; // Relayer addresses which can be trusted to provide accurate option trades EnumerableSet.AddressSet whitelistedRelayers; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function getParams( Layout storage l, address base, address underlying ) internal view returns (bytes32) { return l.parameters[base][underlying].params; } function parseParams(bytes32 input) internal pure returns (int256[] memory params) { params = new int256[](PARAM_AMOUNT); // Value to add to negative numbers to cast them to int256 int256 toAdd = (int256(-1) >> PARAM_BITS) << PARAM_BITS; assembly { let i := 0 // Value equal to -1 let mid := shl(PARAM_BITS_MINUS_ONE, 1) for { } lt(i, PARAM_AMOUNT) { } { let offset := sub(START_BIT, mul(PARAM_BITS, i)) let param := shr( offset, sub( input, shl( add(offset, PARAM_BITS), shr(add(offset, PARAM_BITS), input) ) ) ) // Check if value is a negative number and needs casting if or(eq(param, mid), gt(param, mid)) { param := add(param, toAdd) } // Store result in the params array mstore(add(params, add(0x20, mul(0x20, i))), param) i := add(i, 1) } } } function formatParams(int256[5] memory params) internal pure returns (bytes32 result) { int256 max = int256(1 << PARAM_BITS_MINUS_ONE); unchecked { for (uint256 i = 0; i < PARAM_AMOUNT; i++) { require(params[i] < max && params[i] > -max, "Out of bounds"); } } assembly { let i := 0 for { } lt(i, PARAM_AMOUNT) { } { let offset := sub(START_BIT, mul(PARAM_BITS, i)) let param := mload(add(params, mul(0x20, i))) result := add( result, shl( offset, sub(param, shl(PARAM_BITS, shr(PARAM_BITS, param))) ) ) i := add(i, 1) } } } }
@inheritdoc IERC1155/
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); }
596,913